How can I get an event that needs to be raised every time a control is changed?

I have a long form with a bunch of CheckBox, and sometimes with some occurrences of TextBox. I want the event to occur at any time when a control has been changed (i.e., any CheckBox state has changed or any TextBox.Text has changed). Is there a global way to do this without adding an event handler to each control?

+4
source share
4 answers

One of the advantages of WPF and its declarative nature is that events are inherited down the visual tree.

<Window x:Class="MyApplication.MainWindow" .... TextBox.TextChanged="TextBox_TextChanged" CheckBox.Checked="CheckBox_Checked"> 

All TextBox and CheckBox inherit these event handlers. The same approach can be applied to other controls, such as Grid , so only the controls in the grid are affected.

+7
source

One way is to subclass the CheckBox and TextBox classes and implement the necessary handlers in these classes.

You still need to go through your application and replace the standard CheckBox and TextBox your classes.

+1
source

You can use TextBoxBase.TextChanged = "MainWindow_OnTextChanged" in a window or user control.

+1
source

In WPF there are so-called class events. Put this in the form constructor:

 EventManager.RegisterClassHandler(typeof(TextBox), TextBox.TextChangedEvent, new RoutedEventHandler(AnyTextBox_OnTextChanged)); 

Thus, you register a TextChanged event TextChanged for all text fields. Similar to the checkboxes:

 EventManager.RegisterClassHandler(typeof(CheckBox), CheckBox.CheckedEvent, new RoutedEventHandler(AnyCheckBox_OnChecked)); 
+1
source

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


All Articles