C#学习教程:如何为Combobox的特定项目着色我怎样才能做到这一点?我试过了,但我无法让它工作。我的代码如下:privateclassComboBoxItem{publicintValue{get;放;}公共字符串文本{得到;放;}publicboolSelectable{get;放;}}privatevoidForm1_Load(objectsender,EventArgse){this.comboBox1.ValueMember="Value";this.comboBox1.DisplayMember="文字";this.comboBox1.Items.AddRange(new[]{newComboBoxItem(){Selectable=true,Text="Selectable0",Value=0,},newComboBoxItem(){Selectable=true,Text="Selectable1",Value=1},newComboBoxItem(){Selectable=true,Text="Selectable2",Value=2},newComboBoxItem(){Selectable=false,Text="Unselectable",Value=3},newComboBoxItem(){Selectable=true,Text="Selectable3",Value=4},newComboBoxItem(){Selectable=false,Text="Unselectable",Value=5},});this.comboBox1.SelectedIndexChanged+=(cbSender,cbe)=>{varcb=cbSenderasComboBox;if(cb.SelectedItem!=null&&cb.SelectedItemisComboBoxItem&&((ComboBoxItem)cb.SelectedItem).Selectable==false){//取消选择项目cb.SelectedIndex=-1;}};我在C#.NET中工作您需要将ComboBoxItem上的前景属性设置为您需要的颜色。newComboBoxItem(){Selectable=false,Text="Unselectable",Value=3,Foreground=Brushes.Red},MSDNpage您需要将ComboBox.DrawMode设置为OwnerDrawxxx并编写DrawItem事件脚本,例如:privatevoidcomboBox1_DrawItem(对象发送者,DrawItemEventArgse){e.DrawBackground();//跳过没有有效索引if(e.Index>=0){ComboBoxItemcbi=(ComboBoxItem)comboBox1.Items[e.Index];图形g=e.Graphics;画笔brush=newSolidBrush(e.BackColor);画笔tBrush=newSolidBrush(cbi.Text=="Unselectable"?Color.Red:e.ForeColor);g.FillRectangle(brush,e.Bounds);e.Graphics.DrawString(comboBox1.Items[e.Index].ToString(),e.Font,tBrush,e.Bounds,StringFormat.GenericDefault);刷.处置();tBrush.Dispose();}e.DrawFocusRectangle();显然,这部分cbi.Text=="Unselectable"不好。由于您已经有一个PropertySelectable,它实际上应该是!cbi.Selectable”。当然,您必须确保该属性与文本同步。以上就是C#学习教程的全部内容:如何给combobox的具体item上色。如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文收集自网络,不代表立场。如涉及侵权请点击右侧联系管理员删除。如需转载请注明出处:
