今天的博客将介绍如何实现ListViewItem双击事件绑定到ViewModel中的Command。实现方法借助了Style中的EventSetter,请看下面的详细代码:
在Code Behind中,
private void OnListViewItemDoubleClick(object sender, MouseButtonEventArgs e) { var vm = this.DataContext as MainViewModel; vm.EditCommand.Execute(); }
具体的ViewModel中执行需要的操作即可。这样不会打破MVVM模式。
class MainViewModel { private ObservableCollection_users; public ObservableCollection Users { get { if(_users == null) { _users = new ObservableCollection (); } 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上。
感谢您的阅读,代码点击下载。