2015-03-31 39 views
2

我已经将DataTable设置为WPF DataGrid的ItemsSource。 现在我有一个上下文菜单来删除任何行。该命令在具有DataTable对象的视图模型中处理。但我需要提出命令的那一行。如何做呢? 什么是命令参数?在上下文菜单中获取行命令参数mvvm

+0

P租用数据表和命令设置的XAML代码。 :-) – Anders 2015-03-31 06:23:53

+0

Dhanashree 2015-03-31 06:34:26

+0

Dhanashree 2015-03-31 06:34:35

回答

0

由于ContextMenu不是可视树的一部分,因此我们需要创建一个Freezable作为代理,以便能够联系DataGrid以获取选定的行。 这是一个快速和肮脏的代理。您可以更改属性类型,以满足您的DataContext类型,使设计时绑定验证工作:

class DataContextProxy : Freezable 
{ 
    public static readonly DependencyProperty DataProperty = DependencyProperty.Register("Data", typeof(object), typeof(DataContextProxy)); 


    //Change this type to match your ViewModel Type/Interface 
    //Then IntelliSense will help with binding validation 
    public object Data 
    { 
     get { return GetValue(DataProperty); } 
     set { SetValue(DataProperty, value); } 
    } 

    protected override Freezable CreateInstanceCore() 
    { 
     return new DataContextProxy(); 
    } 
} 

然后你把它放在你的DataGrid:

<DataGrid x:Name="grdData"> 
    <DataGrid.Resources> 
     <DataContextProxy x:Key="Proxy" 
          Data="{Binding ElementName=grdData}"/> 
    </DataGrid.Resources> 
    <DataGrid.ContextMenu> 
     <ContextMenu> 
      <MenuItem Command="{Binding DeleteCommand}" 
         CommandParameter="{Binding Data.SelectedItems, Source={StaticResource Proxy}" 
         Header="Delete"/> 
     </ContextMenu> 
    </DataGrid.ContextMenu>  

现在,在您的视图模型,在DeleteCommand CanExecuteExecute处理程序中:

private bool DeleteCanExecute(object obj) 
{ 
    var rows = obj as IList; 
    if (rows == null) 
     return false; 
    if (rows.Count == 0) 
     return false; 
    return rows.OfType<DataRowView>().Any(); 
} 
private void DeleteExecute(object obj) 
{ 
    var rows = obj as IList; 
    if (rows != null) 
     foreach (DataRowView rowView in rows) 
     { 
      var row = rowView.Row; 
      //Handle deletion 
     } 
}