在视图模型中将DataGrid控件的选定项绑定到Command?

问题描述

| 我试图将当前选定的对象(行)放在
DataGrid
控件中,并使用
ICommand
将它们直接发送到视图模型(MVVM模式),而XAML代码后面没有任何代码。 因为a2ѭ实现了Command属性,所以我已经使用Button完成了此操作,而
DataGrid
则没有。看来使用按钮时在视图和视图模型之间使用命令是惯例,但是其他控件呢? 有没有办法获取当前选定的项目并将其通过命令发送到视图模型?     

解决方法

这是有关该主题的文章。它与Silverlight有关,但该指南对WPF也应该有用。基本上,它说使用EventToCommand之类的东西(来自MVVMLight Toolkit)将
SelectionChanged
事件转换为ICommand。     ,我喜欢使用此处找到的代码。它是一些AttachedProperties,可让您将Commands连接到几乎任何事件
<DataGrid
    local:CommandBehavior.Event=\"MouseDown\" 
    local:CommandBehavior.Command=\"{Binding SomeCommand}\"
    local:CommandBehavior.CommandParameter=\"{Binding SelectedItem}\"/>