WPF - 将数据模板绑定到 ViewModel,而不是单个记录



我有一个包含 telerik RadGridView 的 WPF 用户控件。控件的数据上下文正在设置为 MyViewModel 类的实例。 类具有 myRecords 属性,类型为 ObservableCollection。RadGridView因此受到约束:

ItemsSource="{Binding myRecords}"

在 RadGridView 中,我定义了许多列,这些列包含绑定到 MyRecord 属性的数据模板。 这工作正常。

我添加了一个包含删除按钮的列。 或者更确切地说,它包含一个数据模板,其中包含一个标记为"删除"的按钮。 这绑定到记录上定义的命令:

<telerik:GridViewColumn.CellTemplate>
    <DataTemplate>
        <Button 
                Command="{Binding deleteCommand}"
                CommandParameter="{Binding}">
            <Label>Delete</Label>
        </Button>
    </DataTemplate>
</telerik:GridViewColumn.CellTemplate>

这工作正常。 我在 MyRecord 上定义的 ICommand 属性将执行。

但事情是这样的 - 这不是我想要这段代码的地方。 我不想在MyRecord上运行方法,我想在MyViewModel上运行一个方法,传递适当的MyRecord作为参数。 上面的 CommandParameter="{Binding}" 元素传递了相应的 MyRecord,因此该部分没问题。 但是我一直无法弄清楚如何将按钮的命令绑定到 MyViewModel 对象上的 ICommand,而不是 MyRecord 上的 ICommand。

我一直在玩RelativeSource和AncestorType,但一无所获。

帮助将不胜感激。

一种可能的方法是使用视图模型作为记录,它将包装您的模型记录,并包括一个 ICommand 引用。 初始化每条记录时视图每条记录一个模型

recordViewModel.deleteCommand = myViewModel.deleteCommand;

其中 recordViewModel 和 myViewModel 是相应类的实例。

这样,当单击行中的"删除"按钮时,将执行父数据上下文中的删除命令。

更新:我找到了一个潜在的替代解决方案,您可以在其中绑定到不同的元素,这样您就不会局限于项目的数据上下文,而是使用您指定的任何元素的数据上下文。

Command="{Binding DataContext.MyCommand, ElementName=LayoutRoot}"

参考资料: http://blog.kevindockx.com/post/MVVM-challenge-binding-to-a-command-from-inside-an-ItemsControl-DataTemplate.aspx

你可以使用FindAncestor来做这个,像这样:{Binding DataContext.DeleteCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}

我认为这将是一个更好的解决方案。

最新更新