cjm3407
cjm3407

Reputation: 43

ListBoxItem stealing Mouse clicks from ListBox

I am using MouseBindings in the style of my ListBoxItem.

<MouseBinding MouseAction="LeftClick" Command="{Binding    
DataContext.ViewWorkingImprovementAssetCommand}" CommandParameter="{Binding}"/>

Specifically, I am using the LeftClick command to fire a command in the view model. The issue is the item does not getting selected in the ListBox because the mouse event is not getting to the list box. So is there a way to pass the event to the parent control (ListBox)?

I can get this thing to work if I use an interaction trigger on the ListBox for SelectionChanged, but the problem is re-clicking an already selected item won't fire the event as the name suggests. And when my list only has one item that poses a problem.

<i:Interaction.Triggers>
    <i:EventTrigger EventName="SelectionChanged">
         <i:InvokeCommandAction Command="{Binding ViewWorkingImprovementAssetCommand}" 
                                CommandParameter="{Binding ElementName=RemovedImprovementAssetsListBox, Path=SelectedItem}" />
    </i:EventTrigger>
</i:Interaction.Triggers>

Any ideas?

Upvotes: 1

Views: 1199

Answers (2)

Jay
Jay

Reputation: 323

Add a handler on the ListBox for PreviewMouseDown.

private void myListBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    MyObject entry = null;

    // did user click on a list entry?
    var pos = e.GetPosition(myListBox);
    var elem = myListBox.InputHitTest(pos);
    if (elem is FrameworkElement && (elem as FrameworkElement).DataContext != null)
    {
        ListBoxItem item = myListBox.ItemContainerGenerator.ContainerFromItem((elem as FrameworkElement).DataContext) as ListBoxItem;
        entry = item.DataContext as MyObject;
    }

    // do something with entry

    // if you don't want the event to bubble up, then set e.Handled=true
    // But then you will probably want to set  myListBox.SelectedItem = entry
    e.Handled = true;
}


Upvotes: 0

cjm3407
cjm3407

Reputation: 43

Apparently MouseBinding steals the event and won't pass it through. I solved it using AttachedBehaviors that we already had in our solution. I think taken from this http://marlongrech.wordpress.com/2008/12/13/attachedcommandbehavior-v2-aka-acb/

Final Code solution

<cmd:CommandBehaviorCollection.Behaviors>
<cmd:BehaviorBinding Event="MouseLeftButtonDown" 
                    Command="{Binding  RelativeSource={RelativeSource FindAncestor,  AncestorType=UserControl, AncestorLevel=1}, Path=DataContext.ViewWorkingImprovementAssetCommand}" 
                    CommandParameter="{Binding}"/>
</cmd:CommandBehaviorCollection.Behaviors>

Upvotes: 1

Related Questions