简体   繁体   English

Textbox BackColor不会改变

[英]Textbox BackColor not changing

Can anyone explain why this code is not working? 任何人都可以解释为什么这段代码不起作用?

 protected override void OnMouseDoubleClick(MouseEventArgs e)
        {
            if (this.BackColor == Color.White)
            {
                this.BackColor = Color.Yellow;

            }
            else
            {
                this.BackColor = Color.White;
            }
                base.OnMouseDoubleClick(e);
        }

It worked few times, but mostly does not work. 它工作了几次,但大部分都不起作用。 When i remove the "if" part it works every time, and when i replace "this.BackColor = Color.Yellow" with some other code it also works. 当我删除“if”部分时,它每次都有效,当我用其他代码替换“this.BackColor = Color.Yellow”时,它也有效。 Would be very grateful if some could tell what am i doing wrong. 如果有人能说出我做错了什么,我将非常感激。

It doesn't work only on first double click (it works but sets the color to White not Yellow as you presumably expect) because == operator compares Name and ARGB properties of the color, not only the ARGB property. 它不能仅在第一次双击时起作用(它可以正常工作,但将颜色设置为白色而不是黄色),因为==运算符比较颜色的名称和ARGB属性,而不仅仅是ARGB属性。 Although on first doubleclick ARGB values are the same (ARGB=(255, 255, 255, 255)) , names are not because the initial BackColor property has the name "Window" and the Color.White has the value of the Name property "White" and therefore they are not the same. 虽然在第一次双击时ARGB值相同(ARGB=(255, 255, 255, 255)) ,但名称不是因为初始BackColor属性具有名称“Window”而Color.White具有Name属性的值“白色“因此它们不一样。 You could check that yourself in debugger. 您可以在调试器中检查自己。

To avoid the problem you could rewrite your code as follows: 为避免此问题,您可以按如下方式重写代码:

protected override void OnMouseDoubleClick(MouseEventArgs e)
{
      //compare ARGB values
      if (this.BackColor.ToArgb() == Color.White.ToArgb())
      {
           this.BackColor = Color.Yellow;

      }
      else
      {
           this.BackColor = Color.White;
      }
      base.OnMouseDoubleClick(e);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM