设置一个ReadOnly TextBox默认BackColor [英] Setting a ReadOnly TextBox default BackColor

查看:109
本文介绍了设置一个ReadOnly TextBox默认BackColor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 TextBox ,它设置为 ReadOnly

有时 TextBox 可用于编辑,并且 BackColor 发生更改(指示该值是否有效)。< br>
如果我想将 TexBox 设置回 ReadOnly ,则 TextBox 不会获取 ReadOnly BackColor > TextBox 获取。

我应该怎么做才能再次获得原始颜色?

我意识到我可以手动将颜色设置为 SystemColors.Control ,但这是正确的方法吗?

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"?

这是一个简单的演示代码。
如果要使用 SystemColors.Control ,我将在 ReadOnlyChanged 事件中进行更改。

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...
}


推荐答案

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

You have to set BackColor to the look of a ReadOnly TextBox's BackColor, that is 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 :

You may need a variable to store the current BackColor every time your TextBox's BackColor changes:

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;
}

这篇关于设置一个ReadOnly TextBox默认BackColor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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