One Event for all TextBoxes

2019-02-17 08:55发布

问题:

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! :)

回答1:

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;
}


回答2:

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


回答3:

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;
}


回答4:

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;



回答5:

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:

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(); } } });



回答7:

TextBox T = (TextBox)sender;

You can use sender