Determine which text field fired the modified text event

I have several text fields that are dynamically generated using code.

I would like to be able to assign a common event handler for all text fields to text that has changed, and then inside the handler to determine which text field the event fired.

The code I have is:

txtStringProperty.TextChanged += TextBoxValueChanged; private void TextBoxValueChanged(object sender, RoutedEventArgs e) { string propertyName = // I would like the name attribute of the textbox here } 

Please let me know if you need more information.

+4
source share
3 answers

The sender parameter contains which control triggered the event. You can pass it to a TextBox and get the name property from it:

 string propertyName = ((TextBox)sender).Name; 
+7
source

Paste the object sender (your text box in which the event occurred) on the TextBox .

If you need only one property, write

 string propertyName = ((TextBox)sender).Name; 

But when more than one property is required, it is better to create a Textbox variable and use it as.

 TextBox txtbox = (TextBox)sender; 

Then you can use any property like

 string propertyName = txtbox.Name; MessageBox.Show(proptertyName); MessageBox.Show(txtbox.Content.ToString()); 
+2
source

My advice is to look at the base class hierarchy on MSDN and just select the control and retrieve the properties defined on it:

 var name = ((ContentControl) sender).Name; 

this is also good practice for a more general implementation, because casting it to a "TextBox" means that you can only apply processing logic to this type of control.

0
source

Source: https://habr.com/ru/post/1412364/


All Articles