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):
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 TextBox
es?). This can be achieved by handling the GotFocus
event on the ListBoxItem
s:
<ListBox>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<EventSetter Event="GotFocus" Handler="ListBoxItem_GotFocus"/>
</Style>
</ListBox.ItemContainerStyle>
<TextBox/>
<TextBox/>
</ListBox>
The code:
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.