保留从组合框中选择的项目的颜色:代码附加 [英] Retaining the color of an item selected from a combobox : Code- Attached

查看:59
本文介绍了保留从组合框中选择的项目的颜色:代码附加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个下拉列表(在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.


这篇关于保留从组合框中选择的项目的颜色:代码附加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆