当鼠标左键单击列表框中的项目时,如何执行功能? 我不能使用SelectChanged,因为我也要右键单击,并且右键单击该项目时,还要执行功能SelectChanged。
或者如何选择SelectChange方法(如果事件是单击鼠标右键或鼠标左键
)答案 0 :(得分:0)
WPF:
XAML:安装System.Windows.Interactivity.WPF nuget库
<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>
使用MVVMLight库用于RelayCommand和ViewModelBase的ViewModel.cs
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: 取自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
}
}
}
答案 1 :(得分:0)
listBoxG.AddHandler(UIElement.MouseLeftButtonUpEvent, new RoutedEventHandler(OnMouseLeftButtonUp_listBoxG), true);
public void OnMouseLeftButtonUp_listBoxG(Object sender, RoutedEventArgs e)
{
// something
}