原文:
WPF中如何将ListViewItem双击事件绑定到Command
今天的博客将介绍如何实现ListViewItem双击事件绑定到ViewModel中的Command。实现方法借助了Style中的EventSetter,请看下面的详细代码:
<ListView ItemsSource="{Binding Users}"> <ListView.ItemTemplate> <DataTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="2*" /> <ColumnDefinition Width="3*" /> </Grid.ColumnDefinitions> <TextBlock Text="{Binding Name}" VerticalAlignment="Center" HorizontalAlignment="Center" /> <TextBlock Grid.Column="1" Text="{Binding Birthday}" VerticalAlignment="Center" HorizontalAlignment="Center" /> <TextBlock Grid.Column="2" Text="{Binding Address}" VerticalAlignment="Center" HorizontalAlignment="Center" /> </Grid> </DataTemplate> </ListView.ItemTemplate> <ListView.ItemContainerStyle> <Style TargetType="{x:Type ListViewItem}"> <Style.Setters> <EventSetter Event="MouseDoubleClick" Handler="OnListViewItemDoubleClick" /> </Style.Setters> </Style> </ListView.ItemContainerStyle> </ListView>
在Code Behind中,
private void OnListViewItemDoubleClick(object sender, MouseButtonEventArgs e) { var vm = this.DataContext as MainViewModel; vm.EditCommand.Execute(); }
具体的ViewModel中执行需要的操作即可。这样不会打破MVVM模式。
class MainViewModel { private ObservableCollection<User> _users; public ObservableCollection<User> Users { get { if(_users == null) { _users = new ObservableCollection<User>(); } return _users; } } public DelegateCommand EditCommand { get; private set; } public MainViewModel() { Users.Add(new User() { Name = "Tom", Address = "WUXI IPARK", Birthday = new DateTime(2000,1,1) }); Users.Add(new User() { Name = "Jack", Address = "WUXI IPARK", Birthday = new DateTime(2000, 1, 1) }); Users.Add(new User() { Name = "Jerry", Address = "WUXI IPARK", Birthday = new DateTime(2000, 1, 1) }); Users.Add(new User() { Name = "Hellen", Address = "WUXI IPARK", Birthday = new DateTime(2000, 1, 1) }); EditCommand = new DelegateCommand(Edit); } private void Edit() { System.Diagnostics.Debug.WriteLine("MouseDoubleClick Command."); } }
通过上面的方式就很简单的将ListView中的MouseDoubleClick事件绑定到Command上。
感谢您的阅读,代码点击这里下载。