2

我的表单有以下代码:

    private void txt1_Enter(object sender, EventArgs e)
    {
        txt1.SelectAll();
        txt1.BackColor = Color.LightBlue;
    }

    private void txt2_Enter(object sender, EventArgs e)
    {
        txt2.SelectAll();
        txt2.BackColor = Color.LightBlue;            
    }

    private void txt1_Leave(object sender, EventArgs e)
    {
        txtThermalConductivity.BackColor = Color.White;
    }

    private void txt2_Leave(object sender, EventArgs e)
    {
        txtThermalConductivity.BackColor = Color.White;
    }

我的表单上还有另外 20 个文本框,我想为它们做同样的事情。是否可以结合所有进入事件和所有离开事件,所以我总共有两个事件而不是 44 个单独的事件?

4

3 回答 3

4

在您的设计器视图中,选择每个文本框并将EnterLeave事件设置为指向每个文本框的单个实现。

然后你可以这样做:

private void txt_enter(object sender, EventArgs e) {
    ((TextBox)sender).BackColor = Color.LightBlue;
}

private void txt_leave(object sender, EventArgs e) {
    ((TextBox)sender).BackColor = Color.White;
}

此外,SelectAll不是必需的,因为您正在设置整个文本框的背景颜色.. 而SelectionColor不是RichTextBox.

于 2013-04-07T23:08:20.840 回答
1

您可以手动添加或遍历表单中的所有文本框(在此处找到扩展方法GetChildControls

foreach (TextBox textBox in this.GetChildControls<TextBox>())
{
    textBox.Enter += new EventHandler(TextBox_Enter);
    textBox.Leave += new EventHandler(TextBox_Leave);
}

可以从 Form 的 Load 事件中调用上述内容。

通过将发送者转换为 TextBox,事件侦听器现在可以如下所示。

 private void TextBox_Enter(object sender, EventArgs e)
{
    TextBox txtBox = (TextBox)sender;
    txtBox .SelectAll();
    txtBox .BackColor = Color.LightBlue;            
}

private void TextBox_Leave(object sender, EventArgs e)
{
    TextBox txtBox = (TextBox)sender;
    txtBox.BackColor = Color.White;
}
于 2013-04-07T23:10:27.753 回答
0

是的,只需使用以下内容:

private void tbLeave(object sender, EventArgs e) {
((TextBox) sender).BackColor = Color.White;
}

将控件事件声明设置为指向此函数。

您也可以对 Leave() 事件执行相同的操作。

(只是要说一点,我更喜欢尽可能在客户端处理这种事情。)

于 2013-04-07T23:09:58.527 回答