YosiFZ
YosiFZ

Reputation: 7900

ListBox mouse left click event

I have this ListBox in my XAML file:

<ListBox ItemsSource="{Binding Path=MyList}" Name="HistoryListBox" BorderThickness="0"
         Grid.Row="1" Margin="-2,0,0,0" ScrollViewer.CanContentScroll="False" 
         SelectionChanged="History_ListBox_Selection_Changed">
    <ListBox.Resources>
        <!--Defines a context menu-->
        <ContextMenu x:Key="MyElementMenu">
            <MenuItem Header="Delete from History" Click="MenuItemDelete_Click"/>
        </ContextMenu>

        <!--Sets a context menu for each ListBoxItem in the current ListBox-->
        <Style TargetType="{x:Type ListBoxItem}">
            <Setter Property="ContextMenu" Value="{StaticResource MyElementMenu}"/>
        </Style>
    </ListBox.Resources>
</ListBox>

As you can see it's have the option that when the user click on item it's call

History_ListBox_Selection_Changed

And when the user select Rightclick on ListBox item the ContextMenu Appear.

Now i have a problem that when a user click on the Right button the History_ListBox_Selection_Changed trigger and then the ContextMenu Appear.

How i can make the History_ListBox_Selection_Changed work only when left click on the mouse?

Upvotes: 1

Views: 2063

Answers (2)

Ravi Patel
Ravi Patel

Reputation: 463

Change "SelectionChanged" Event to "MouseLeftButtonUp" or "MouseLeftButtonDown".

Upvotes: 0

Colin
Colin

Reputation: 551

Change your code

<Style TargetType="{x:Type ListBoxItem}">
    <Setter Property="ContextMenu" Value="{StaticResource MyElementMenu}"/>
</Style>

to

<Style TargetType="{x:Type ListBoxItem}">
    <Setter Property="ContextMenu" Value="{StaticResource MyElementMenu}"/>
    <EventSetter Event="MouseLeftButtonUp" Handler="History_ListBox_Selection_Changed">
    </EventSetter>
</Style>

And then remove SelectionChanged="History_ListBox_Selection_Changed".

Upvotes: 1

Related Questions