One Event for all TextBoxes

2019-02-17 08:59发布

I´m doing simple program in WPF C# and I have many TextBoxes - each TextBox do same thing and I´m very lazy to write each Event for each TextBox. So, Is there any way how to serve all TextBox by one Event?

There is a short code:

private void OnMouseLeft(object sender, MouseButtonEventArgs e)
{
    TextBox1.Text = string.Empty;
    TextBox1.Foreground = Brushes.Black;
}
private void OnMouseLeft1(object sender, MouseButtonEventArgs e)
{
    TextBox2.Text = string.Empty;
    TextBox2.Foreground = Brushes.Black;
}

Thank You! :)

7条回答
Juvenile、少年°
2楼-- · 2019-02-17 09:55

You can assign multiple events to the same event handler. These events can be from the same control and/or different controls.

        TextBox t = new TextBox();
        t.MouseLeftButtonUp += new MouseButtonEventHandler(OnMouseLeft);
        t.MouseLeftButtonDown += new MouseButtonEventHandler(OnMouseLeft);
        TextBox t2 = new TextBox();
        t2.MouseLeftButtonUp += new MouseButtonEventHandler(OnMouseLeft);

Then you just handle which textbox by casting the sender.

((TextBox)sender).Property = value;

查看更多
登录 后发表回答