10

I have a TextBox which is set to be ReadOnly.
At some point that TextBox is being available for editing, and it's BackColor changes (It is indicating if the value is valid).
If I want to set the TexBox back to ReadOnly, the TextBox doesn't get back the original BackColor that a ReadOnly TextBox gets.
What should I do in order to get the original color again?
I realize I can set the color manually to SystemColors.Control, but is this the "right way"?

Code Sample

This is a simple code for demonstration. If SystemColors.Control is the way to go, I will change it in the ReadOnlyChanged event...

private void button1_Click(object sender, EventArgs e)
{
    //At this point this.textBox1 is ReadOnly
    this.textBox1.ReadOnly = false;
    this.textBox1.BackColor = Color.Orange;


    /*this.textBox1.BackColor = SystemColors.Control;*/ //Is this the right way?
    this.textBox1.ReadOnly = true; //Textbox remains orange...
}
4

3 回答 3

13

您必须设置BackColor为 a 的外观ReadOnly TextBox's BackColor,即Color.FromKnownColor(KnownColor.Control)

//this is the ReadOnlyChanged event handler for your textbox
private void textBox1_ReadOnlyChanged(object sender, EventArgs e){
   if(textBox1.ReadOnly) textBox1.BackColor = Color.FromKnownColor(KnownColor.Control);
}

每次 TextBox 的 BackColor 更改时,您可能需要一个变量来存储当前的 BackColor:

Color currentBackColor;
bool suppressBackColorChanged;
private void textBox1_BackColorChanged(object sender,EventArgs e){
   if(suppressBackColorChanged) return;
   currentBackColor = textBox1.BackColor;
}
private void textBox1_ReadOnlyChanged(object sender, EventArgs e){
   suppressBackColorChanged = true;
   textBox1.BackColor = textBox1.ReadOnly ? Color.FromKnownColor(KnownColor.Control) : currentBackColor;
   suppressBackColorChanged = false;
}
于 2013-08-04T05:59:27.347 回答
3

是的,没关系。没有理由不能使用 SystemColors 为控件指定所需的颜色。我从来没有听说过任何WinForms会导致控件在设置时自动恢复为默认颜色的事情ReadOnly = true

我想另一种选择是创建一个名为 or 的类级别变量textBox1OriginalColor并将其设置在表单的Load事件中。然后,如果您认为将来有人可能将文本框的默认背景颜色设置为,例如,设计器中的蓝色或其他东西,那么您确切地知道最初显示表单时它是什么。

于 2013-08-04T05:26:54.280 回答
3

我知道这是一个老问题,但为了后代:

TextBox 以及许多其他控件依赖 Color.Empty 来决定是否显示其默认颜色。

要将 TextBox 设置回系统默认值(无论状态如何):

textBox1.BackColor = Color.Empty;
于 2019-03-22T18:18:21.667 回答