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条回答
叛逆
2楼-- · 2019-02-17 09:31

The 'sender' parameter will be the TextBox itself. So just write one function and attach them all to that one function.

private void OnMouseLeft(object sender, MouseButtonEventArgs e)
{
    var textBox = (TextBox)sender;
    textBox.Text = string.Empty;
    textBox.Foreground = Brushes.Black;
}
查看更多
Lonely孤独者°
3楼-- · 2019-02-17 09:37

Attach same handler to all textboxes and use sender argument to get textbox instance which raised event:

private void OnMouseLeft(object sender, MouseButtonEventArgs e)
{
    TextBox textBox = (TextBox)sender;
    textBox.Text = String.Empty;
    textBox.Foreground = Brushes.Black;
}
查看更多
手持菜刀,她持情操
4楼-- · 2019-02-17 09:44

try this for all textbox not allowed numeric value only text..

$('input[type=text]') .keydown(function (e) {
if (e.shiftKey || e.ctrlKey || e.altKey) { e.preventDefault(); } else { var key = e.keyCode; if (!((key == 8) || (key == 32) || (key == 46) || (key >= 35 && key <= 40) || (key >= 65 && key <= 90))) { e.preventDefault(); } } });

查看更多
Explosion°爆炸
5楼-- · 2019-02-17 09:50

Add each taxBox to the same method and then get the TextBox clicked as shown, I did not this but it should work or at least get you going in the right direction. I hop it helps.

textBox.MouseClick += new MouseEventHandler(textBox_MouseClick);

 private void textBox_MouseClick(object sender, MouseEventArgs e)
 {
      if (e.Button == System.Windows.Forms.MouseButtons.Left)
      {
           TextBox textBox = sender as TextBox;
           textBox.Text = string.Empty;
           textBox.Forground = Brushes.Black;
      }
 }
查看更多
戒情不戒烟
6楼-- · 2019-02-17 09:52
TextBox T = (TextBox)sender;

You can use sender

查看更多
唯我独甜
7楼-- · 2019-02-17 09:55
private void OnMouseLeft(object sender, MouseButtonEventArgs e)
{
    (sender as TextBox).Text = string.Empty;
    (sender as TextBox).Foreground = Brushes.Black;
}
查看更多
登录 后发表回答