Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Passing events from child to parent control's built in handler in WPF

0.00/5 (No votes)
26 Jul 2011 1  
In WPF, you can use the method UIElement.AddHandler(RoutedEvent, Delegate, Boolean) to specify that the UIElement should receive all events, including those that have been handled. Just subscribe your ListBox to the MouseDown event this way (you might do this in your custom control's...

In WPF, you can use the method UIElement.AddHandler(RoutedEvent, Delegate, Boolean) to specify that the UIElement should receive all events, including those that have been handled. Just subscribe your ListBox to the MouseDown event this way (you might do this in your custom control's constructor):


C#
listBox.AddHandler(Mouse.MouseDownEvent, ListBox_MouseDown, true);

Then in ListBox_MouseDown, you'll need to extract the item that has been clicked. It can be done by iterating through ListBox items and searching for the one that is the parent for the RoutedEventArgs.OriginalSource of the event.


But it seems to me that what you really need is setting the ListBox.SelectedItem to the TextBox that has focus (what if the user tabs through your TextBoxes?). This can be achieved by handling the GotFocus event on the ListBoxItems:


XML
<ListBox>
  <ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
      <EventSetter Event="GotFocus" Handler="ListBoxItem_GotFocus"/>
    </Style>
  </ListBox.ItemContainerStyle>
		
  <TextBox/>
  <TextBox/>
</ListBox>

The code:


C#
private void ListBoxItem_GotFocus(object sender, RoutedEventArgs e)
{
  var listBoxItem = sender as ListBoxItem;
  listBoxItem.IsSelected = true;
}

This way is perhaps closer to your real UI logic, and it gives higher performance. This is because in WPF, setting RoutedEvent.Handled to true does not stop the event from bubbling or tunneling if it does. They continue propagating through the element tree, but only handlers registered as shown above are invoked on the way. Thus, you have doubled the number of MouseDown events raised in the system, which is obviously slower than following my advice.


Best regards,

Pavel.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here