问题
I have a really strange problem. I have multiple TextBoxes for username/passwords, and a CheckBox beside every user/pass group. When user clicks on the CheckBox, and if he checked it, the username and password TextBox beside it become enabled and focus is set to username TextBox. If user unchecked the CheckBox the TextBoxes beside it become disabled. However the border of one TextBox stays different than other disabled TextBoxes.
See:
I've thought it was a focus problem, so I've changed the code - when user unchecks the CheckBox it first focuses on some other element on the form and then disables it, but it still does the same thing. Any ideas on what could cause the problem?
回答1:
So far as I can tell, this is a bug in the way the system is rendering the control's disabled state. I've created the following code to simulate this issue. The code is a bit verbose but I made it so in order easily understand the logic flow.
I created a form, with : 4 textboxes named txtBox1, txtBox2, txtBox3 and txtBox4 4 checkboxes named chkBox1, chkBox2, chkBox3 and chkBox4
Set the Enabled property of each textbox to False (I did this at design time)
private void Form1_Load(object sender, EventArgs e) {
chkBox1.CheckedChanged += chkBox_CheckedChanged;
chkBox2.CheckedChanged += chkBox_CheckedChanged;
chkBox3.CheckedChanged += chkBox_CheckedChanged;
chkBox4.CheckedChanged += chkBox_CheckedChanged;
}
private void chkBox_CheckedChanged(object sender, EventArgs e) {
var chkBox = ((CheckBox)sender);
var controlSet = chkBox.Name.Substring(6,1);
var txtName = "txtBox" + controlSet;
foreach (var txtBox in Controls.Cast<object>().Where(ctl => ((Control)ctl).Name == txtName).Select(ctl => ((TextBox)ctl))) {
if (chkBox.Checked) {
txtBox.Enabled = true;
txtBox.Focus();
}
else {
//The checkbox stole the focuse when it was clicked, so no need to change.
txtBox.Enabled = false;
}
}
}
Now if you execute this code, you can check the checkboxes to enable the textbox with the same name prefix (1, 2, 3 or 4). This also sets the focus to the Textbox. Now, if you disable a Textbox that has the focus, it shows up differently than other disabled Textboxes.
I tried all kinds of Refresh, Invalidate, etc.. on the controls and Form itself to no avail.
UPDATE
So I found a hack that seems to work. If you set the borderstyle of the textbox to 'None' before disabling, and then reset it afterwards, the odd outline effect doesn't happen.
var borderStyle = txtBox.BorderStyle;
txtBox.BorderStyle = BorderStyle.None;
txtBox.Enabled = false;
txtBox.BorderStyle = borderStyle;
来源:https://stackoverflow.com/questions/7905184/c-sharp-textbox-border-changes-when-it-gets-disabled-compared-to-other-disabled