WinForms在下一个TextBox控件聚焦时设置标签Forecolour

时间:2014-02-12 23:21:22

标签: c# winforms controls selection

确定,

通常的做法是使用Label后跟TextBox。想象一下,我们有三个标签和三个这样的TextBox。

Label1.Text =“用户名”TextBox1.Name =“tbUserName”;
Label2.Text =“用户性别”TextBox2.Name =“tbUserSex”;
Label3.Text =“用户年龄”TextBox3.Name =“tbUserAge”;

当TextBox1聚焦时,我希望Label1.Forecolor为白色,否则为IndianRed
当TextBox2聚焦时,我希望Label2.Forecolor为白色,否则为IndianRed ......等

我以为我可以用TagIndex做到 - 这是正确设置的。我试过TextBox1.GetNextControl(TextBox1,false);但那没用。这是我目前的代码,它不起作用。

private void SetLabelFocus()
    {
        SetAllLablesToDefault();

        foreach (Control ctrl in panel1.Controls)
        {
            if (ctrl is TextBox)
            {
                TextBox tb = ctrl as TextBox;
                if(tb.Focused)
                {
                    foreach (Control ctr in panel1.Controls)
                    {
                        if (ctr is Label)
                        {
                            Label L = ctrl as Label;
                            if (label1.TabIndex == (tb.TabIndex-1))
                            {
                                label1.ForeColor = Color.White;
                            }

                        }
                    }
                }

            }
        }
    }

    private void SetAllLablesToDefault()
    {
        foreach (Control ctrl in panel1.Controls)
        {
            if (ctrl is Label)
            {
                Label c = ctrl as Label;
                c.ForeColor = defaultTextColour;

            }
        }
    }

当在Label2.Enter()中调用SetLabelFocus()时,当前发生的事情所有标签都变为白色......现在可能导致问题的一个问题是标签前缀是应用程序绑定,TextBoxes BackColor也是如此。

无论如何,我怎样才能将以前的标签带到聚焦的TextBox来改变它的前景色?

干杯。

1 个答案:

答案 0 :(得分:1)

这有效:

public Form1() {
  InitializeComponent();

  textBox1.Enter += LabelFocus;
  textBox2.Enter += LabelFocus;
  textBox3.Enter += LabelFocus;
}

void LabelFocus(object sender, EventArgs e) {
  TextBox tb = sender as TextBox;
  if (tb != null) {
    foreach (Label lbl in panel1.Controls.OfType<Label>()) {
      if (lbl.TabIndex == (tb.TabIndex - 1)) {
        lbl.ForeColor = Color.White;
      } else {
        lbl.ForeColor = Color.IndianRed;
      }
    }
  }
}

但它不能很好地扩展,因为它依赖于总是正确设置的TabIndex属性。 Heed Hans的建议是,带有TextBox和Label的UserControl非常简单。