我有一个包含telerik RadGridView的WPF用户控件。控件的数据上下文被设置为MyViewModel类的实例。 MyViewModel类具有类型为ObservableCollection的myRecords属性。 RadGridView因此受到约束:
ItemsSource="{Binding myRecords}"
在RadGridView中,我定义了许多列,其中包含绑定到MyRecords属性的DataTemplates。这很好。
我添加了一个包含删除按钮的列。或者更确切地说,它包含一个DataTemplate,其中包含一个标记为“delete”的按钮。这绑定到记录中定义的命令:
<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上。
我一直在玩RelativeSource和AncestorType,并且无处可去。
帮助将不胜感激。
答案 0 :(得分:1)
一种可能的方法是使用ViewModel进行记录,它将包装模型记录并包含ICommand引用。当为每条记录初始化每个recordViewModel时
recordViewModel.deleteCommand = myViewModel.deleteCommand;
其中recordViewModel和myViewModel是相应类的实例。
这样,当单击行中的Delete按钮时,将执行父DataContext中的deleteCommand。
更新:我找到了一个潜在的替代解决方案,您可以将其绑定到另一个元素,这样您就不会受限于项目的数据上下文,而是使用您指定的任何元素的数据上下文。
Command="{Binding DataContext.MyCommand, ElementName=LayoutRoot}"
答案 1 :(得分:0)
您可以使用FindAncestor进行此操作,如下所示:{Binding DataContext.DeleteCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}
。
我认为这将是一个更好的解决方案。