2
我已經將DataTable設置爲WPF DataGrid的ItemsSource。 現在我有一個上下文菜單來刪除任何行。該命令在具有DataTable對象的視圖模型中處理。但我需要提出命令的那一行。如何做呢? 什麼是命令參數?在上下文菜單中獲取行命令參數mvvm
我已經將DataTable設置爲WPF DataGrid的ItemsSource。 現在我有一個上下文菜單來刪除任何行。該命令在具有DataTable對象的視圖模型中處理。但我需要提出命令的那一行。如何做呢? 什麼是命令參數?在上下文菜單中獲取行命令參數mvvm
由於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 CanExecute
和Execute
處理程序中:
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
}
}
P租用數據表和命令設置的XAML代碼。 :-) – Anders 2015-03-31 06:23:53