Get a WPF ListBox item from MouseLeftButtonDown

elementflow, listbox, mouseevent, wpf

Solution

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 handler of the MouseLeftButtonDown, the "sender" will be the ListBoxItem.

ALSO, if you don't want to use this method, you can call HitTest to find out the Visual object at a specified position:

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;
}

Problem

I want to run some code when the user single clicks on any given `ListBox` item. My setup is a `ListBox` with a custom `ItemsPanelTemplate` (Pavan's ElementFlow). Based on the position data that comes in to `MouseLeftButtonDown` is there a way to tell which item is was clicked? This is made a bit more difficult (or more confusing) by the custom `ItemsPanelTemplate`.

Original source