Wednesday, January 15, 2014

TextInput event on DataGrid

WPF Version 4.0

This had me scratching my head for quite a while. Eventually it was Microsoft's documentation that revealed the way (could be a first!).

The problem is that the TextInput event bubbles, which means the TextBox got a crack at it before the DataGrid. The TextBox marked the event as handled, so it was not getting raised for the DataGrid. However, I vaguely remembered that there is a way to attach an event handler so that it gets raised EVEN FOR HANDLED EVENTS. I found some examples on Google but they are all for C#. The syntax for doing this in VB is as follows...

myDataGrid.AddHandler(TextBox.TextInputEvent, DirectCast(AddressOf myTextInputHandler, RoutedEventHandler), True)

For C#
myDataGrid.AddHandler(TextBox.TextInputEvent, new RoutedEventHandler(myTextInputHandler), true);

This is a very powerful technique because it can also attach handlers for events the target does not directly support. For example, you could attack a click event to a Label which would cause the Label to call your event handler when anything inside that label raised a click event. You can do this even though the Label control does not support the click event. In this case the following would not work.

AddHandler MyLabel.Click, Addressof MyLabelClickHandler

No comments:

Post a Comment