保留从组合框中选择的项目的颜色:代码附加

保留从组合框中选择的项目的颜色:代码附加

问题描述:

我有一个下拉列表(在Windows窗体中使用C#),根据某些条件,其项目以不同的颜色显示。我无法保留所选项目的颜色。





I have a drop-down list(in Windows Forms using C#) whose items appear in different colours according to some conditions. I am unable to retain the colour of a selected item.


public Form1()
     {
         InitializeComponent();

         // cmb.SelectedIndex = 0;



         cmb.Items.Add("1");
         cmb.Items.Add("2");
         cmb.Items.Add("3");
         cmb.Items.Add("4");
         cmb.Items.Add("5");
         cmb.Items.Add("6");

         cmb.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;


     }


          private void cmb_Draw(object sender, DrawItemEventArgs e)
     {
         cmb.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;


         // Draw the background
         e.DrawBackground();

         // Get the item text
         string text = ((ComboBox)sender).Items[e.Index].ToString();

         // Determine the forecolor based on whether or not the item is selected
         Brush brush;

         if (int.Parse( text) > 3 )  // condition check
         {
             brush = Brushes.Red;
         }
         else
         {
             brush = Brushes.Blue;
         }

         // Draw the text
         e.Graphics.DrawString(text, ((Control)sender).Font, brush, e.Bounds.X, e.Bounds.Y);

您可以在表单级范围内使用变量并将其称为LastColor并设置值当您确定前景色时,在IF语句中,当下拉列表选择发生变化时,您可以从静态变量中调用颜色。
You can use a variable at the form level scope and call it something like "LastColor" and set the value for it in the "IF" statement when you determine the forecolor, and then when the dropdown list selection changes you can recall the color from the static variable.