【问题标题】:get row in context menu command parameter mvvm在上下文菜单命令参数 mvvm 中获取行
【发布时间】:2015-06-04 09:30:05
【问题描述】:

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

【问题讨论】:

  • 请发布数据表和命令设置的 XAML 代码。 :-)

标签: wpf mvvm binding datatable datarow


【解决方案1】:

由于 ContextMenu 不是可视化树的一部分,我们需要创建一个 Freezable 来充当代理,以便能够联系 DataGrid 以获取选定的行。 这是一个快速而肮脏的代理。您可以更改属性类型以匹配您的数据上下文类型,以使设计时绑定验证工作:

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>     

现在在您的 viewModel 中,在 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
        }
}      

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-08
    • 2011-04-19
    • 2012-01-01
    • 2017-11-24
    • 1970-01-01
    相关资源
    最近更新 更多