Get Listbox WPF Element from MouseLeftButtonDown

I want to run some code when the user clicks on any given element ListBox. My setup is ListBoxwith custom ItemsPanelTemplate(Pavan ElementFlow). Based on the position data that comes in MouseLeftButtonDown, is there a way to find out which item was clicked? This makes the user a bit more complicated (or confusing) ItemsPanelTemplate.

+3
source share
1 answer

You can have an ItemContainerStyle and specify an EventSetter in it:

<ListBox>
    <ListBox.ItemContainerStyle>
        <Style TargetType="{x:Type ListBoxItem}">
            <EventSetter Event="MouseLeftButtonDown" Handler="ListBoxItem_MouseLeftButtonDown" />
    ...

Then, in the MouseLeftButtonDown handler, the "sender" will be ListBoxItem.

, , HitTest, :

HitTestResult result = VisualTreeHelper.HitTest(myCanvas, pt);

ListBoxItem lbi = FindParent<ListBoxItem>( result.VisualHit );

public static T FindParent<T>(DependencyObject from) 
    where T : class
{
    T result = null;
    DependencyObject parent = VisualTreeHelper.GetParent(from);

    if (parent is T)
       result = parent as T;
    else if (parent != null)
       result = FindParent<T>(parent);

    return result;
}
+12

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


All Articles