C# listbox项目列表item属性自定义方法(背景,前景,字体等等) 每项itemheight的高度
研究了一下午,想在listbox列表中更改选择项的字体颜色,以突出显示,属性里面肯定是没有的,找了半天,原来有个listBox1_DrawItem事件,可是人家是初始化时候自动调用的,我们基本没法控制(用.refresh())好像可以间接调用……
在private void listBox1_DrawItem(objectsender, DrawItemEventArgs e)中, 可以看到DrawItemEventArgs这个类,其实他是对listBox1某一项的属性的打包,如字体,位置等,而在该事件代码中的关键语句e.Graphics.DrawString(listBox1.Items[e.Index].ToString(), e.Font, new SolidBrush(e.ForeColor), e.Bounds,strFormat); 其实就是Graphics对象的DrawString方法,而参数e中的Graphics是如何来的呢。我们接着分析DrawItemEventArgs这个类,他既然是对listBox1某一项的属性的打包,那么我估计其中的Graphics对象就是由listBox1.creatgraphics而来的。好了,到此我们就可以自定义重绘listbox某项的函数了,可任意调用的哦!
关键代码如下:
Graphics aa = listBox1.CreateGraphics();
aa.DrawString(listBox1.Items[1].ToString(),listBox1.Font, new SolidBrush(listBox1.ForeColor), listBox1.GetItemRectangle(1));
修改DrawString中的一些参数,是不是就能得到你想要的!
当然你还可以调用Graphics的其他一些方法,如填充一下,背景前景等等……
真是天高任鸟飞,洞深任你X,呵呵,看完 了?休息一下嘛……
不过,看完了,你有什么意见,咱们共同分享一下啊,我是菜鸟,我不会!



public partial class Form1 : Form { public Form1() { InitializeComponent(); //this.listBox1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable; //this.listBox1.FormattingEnabled = true; //this.listBox1.ItemHeight = 50; //this.listBox1.Items.AddRange(new object[] { //"fsfsf", //"sfs", //"fsfs", //"sf", //"sf", //"sf", //"sfffffffffffffffff"}); listBox1.DrawMode = DrawMode.OwnerDrawVariable; listBox1.ItemHeight = 22; listBox1.DrawItem += new DrawItemEventHandler(listBox1_DrawItem); listBox1.Items.Clear(); this.listBox1.Items.AddRange(new object[] { "fsfsf", "sfs", "fsfs", "sf", "sf", "sf", "sfffffffffffffffff"}); } void listBox1_DrawItem(object sender, DrawItemEventArgs e) { e.DrawBackground(); Brush pBlackBrush = Brushes.White; if ((e.State & DrawItemState.Selected) == DrawItemState.Selected) { e.DrawFocusRectangle(); pBlackBrush = Brushes.Orange; } e.Graphics.FillRectangle(pBlackBrush, e.Bounds); //e.Graphics.DrawString(this.listBox1.Items[e.Index].ToString(), this.listBox1.Font, Brushes.Black, e.Bounds); float fTop = (e.Bounds.Height - e.Font.Height) / 2; RectangleF Rect = new RectangleF(e.Bounds.X,e.Bounds.Y + fTop,e.Bounds.Width,e.Font.Height); e.Graphics.DrawString(this.listBox1.Items[e.Index].ToString(), this.listBox1.Font, Brushes.Black, Rect); } }
浙公网安备 33010602011771号