Mouse interaction in ListBoxItem children (WPF)

Posted by absence on Stack Overflow See other posts from Stack Overflow or by absence
Published on 2010-05-23T20:32:06Z Indexed on 2010/05/24 11:31 UTC
Read the original article Hit count: 409

Filed under:
|
|
|
|

I have a ListBox with an ItemTemplate that contains a control that interacts with the mouse. This interfers with the selection functionality of the ListBox, i.e. clicking a control does not select the item. This is because ListBoxItem sets the Handled property of the mouse event to true in OnMouseLeftButtonDown. I tried the following

protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) {
    base.OnMouseLeftButtonDown(e);
    e.Handled = false;
}

but the ListBoxItem “takes over” the mouse and prevents the control from doing its own interaction. Then I had another idea

protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) {
    base.OnMouseLeftButtonDown(e);
    ((ListBoxItem)VisualTreeHelper.GetParent(VisualTreeHelper.GetParent(VisualTreeHelper.GetParent(this)))).IsSelected = true;
}

which actually works, but feels more like an ugly kludge than an elegant solution. Are there any better solutions that don't rely on the exact contents of the visual tree?

© Stack Overflow or respective owner

Related posts about wpf

Related posts about listbox