Mouse Interaction in ListBoxItem Children (WPF)

I have a ListBox with an ItemTemplate that contains a control that interacts with the mouse. This is due to the functionality of the ListBox selection, i.e. Clicking a control does not select the control. This is because the 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 ListBoxItem "takes over" the mouse and does not allow you to control your 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 depend on the exact contents of the visual tree?

+4
source share
3 answers

I found a way that applies less:

 protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) { base.OnMouseLeftButtonDown(e); Selector.SetIsSelected(this, true); } 

For this to have any effect, the control in the ItemTemplate ListBox needs the following XAML attribute:

 Selector.IsSelected="{Binding IsSelected, Mode=OneWayToSource, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}" 

Two new questions arise:

  • Would it be better to define your own dependency property rather than finding an attachment that is not currently in use?
  • Is there a way to achieve something similar in markup?
0
source

I believe that MouseLeftButtonDown is a tunneling event: you can try using PreviewMouseLeftButtonDown by doing your processing there and then providing e.Handled = false; as you have already tried - this should do the trick!

Hope this helps.

0
source

Here is one simple solution, but, unfortunately, a handler can only be attached in code, not in markup.
An event handler can be added using the handledEventsToo signature of the AddHandler method:

 myListBox.AddHandler(UIElement.MouseDownEvent, new MouseButtonEventHandler(ListBox_MouseDown), true); 

The third parameter is above handledEventsToo , which ensures that this handler will be called regardless of whether it is already marked as Handled (which the ListBoxItem does in the ListBox).

See Marking Routed Events as Processed and Class Handling for an explanation.
See How to connect to the MouseDown event in a ListBox , for example.

0
source

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


All Articles