如何改变ComboBox控件属性DefaultPadding的数值?
问题描述:
使用ComboBox(.NET WindowForm),控件中的文本与控件左边界特近,想改变一下,通常在其他控件,如TextBox中只需要设置Padding属性,但是奇怪的是ComboBox没有Padding属性,只有一个DefaultPadding属性,而且只读的,真令人抓狂啊,如何设置右边距呢?希望有告诉不啬赐教!感激不尽
答
不知道你说的是下拉的还是combobox的文本框的。因为操作系统层面没有支持,所以这个需要重绘实现。
答
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
namespace Q690118
{
class MyComboBox : System.Windows.Forms.ComboBox
{
public MyComboBox()
{
indent = 20;
SetStyles();
}
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
//base.OnPaint(e);
e.Graphics.FillRectangle(SystemBrushes.Control, new Rectangle(e.ClipRectangle.X + 2, e.ClipRectangle.Y + 2, e.ClipRectangle.Width - 20, e.ClipRectangle.Height - 4));
e.Graphics.DrawString(this.Text, this.Font, SystemBrushes.ControlText, new Rectangle(e.ClipRectangle.X + indent, e.ClipRectangle.Y + 4, e.ClipRectangle.Width - 20, e.ClipRectangle.Height - 8));
}
private void SetStyles()
{
SetStyle(ControlStyles.AllPaintingInWmPaint, true);
SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
SetStyle(ControlStyles.ResizeRedraw, true);
SetStyle(ControlStyles.SupportsTransparentBackColor, true);
UpdateStyles();
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
if (m.Msg == 0xF || m.Msg == 0x133)
{
OnPaint(new PaintEventArgs(this.CreateGraphics(), this.DisplayRectangle));
}
}
public int indent { get; set; }
}
}
答
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Q690118
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
myComboBox1.Items.Add("111");
myComboBox1.Items.Add("222");
myComboBox1.Items.Add("333");
myComboBox1.Text = "111";
}
private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
myComboBox1.indent = (int)numericUpDown1.Value;
myComboBox1.Invalidate();
}
}
}