How can I execute an function when mouse left click on a Item in listbox ? I Can't use SelectChanged because I listen also right click, and when I right click on the item it's execute the fuction SelectChanged also.
Or how to detect in SelectChange method, if event it's right click or left
WPF:
XAML: install System.Windows.Interactivity.WPF nuget library
<Window x:Class="WpfApp1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:test="clr-namespace:Test"
mc:Ignorable="d"
Title="Window1">
<Window.DataContext>
<test:MainViewModel/>
</Window.DataContext>
<Grid>
<ListBox ItemsSource="{Binding ListBoxItems}" HorizontalAlignment="Left" Width="216" Height="235" Margin="10,10,0,0" VerticalAlignment="Top">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseLeftButtonUp" >
<i:InvokeCommandAction Command="{Binding ListBoxLeftClickCommand}" CommandParameter="{Binding SelectedItem, RelativeSource={RelativeSource FindAncestor, AncestorType=ListBox}}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ListBox>
</Grid>
</Window>
ViewModel.cs using the MVVMLight library for RelayCommand and ViewModelBase
using System;
using System.Collections.ObjectModel;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
namespace Test
{
public class MainViewModel : ViewModelBase
{
public class TestModel
{
public string Value { get; set; }
public TestModel(string value)
{
this.Value = value;
}
}
public ObservableCollection<string> ListBoxItems { get; set; }
public ICommand ListBoxLeftClickCommand { get; }
public MainViewModel()
{
ListBoxLeftClickCommand = new RelayCommand<object>(DoSomething, selectedItem => true);
ListBoxItems = new ObservableCollection<string>() { "Test1", "Test2" };
}
private void DoSomething(object selectedItem)
{
throw new NotImplementedException();
}
}
}
WinForms: taken from Right Click to select items in a ListBox
this.ListBox.MouseUp += new System.Windows.Forms.MouseEventHandler(this.List_LeftClick);
private void List_LeftClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
int index = this.listBox.IndexFromPoint(e.Location);
if (index != ListBox.NoMatches)
{
// Do something
}
}
}
listBoxG.AddHandler(UIElement.MouseLeftButtonUpEvent, new RoutedEventHandler(OnMouseLeftButtonUp_listBoxG), true);
public void OnMouseLeftButtonUp_listBoxG(Object sender, RoutedEventArgs e)
{
// something
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.