将父ViewModel实例作为DataPamplate的Button命令的CommandParameter传递

时间:2013-12-29 11:18:02

标签: .net wpf xaml data-binding mvvm

我有一个将ItemsSource设置为Collection<ItemViewModel>的ListBox。 ListBox定义了 DataTemplate ,以很好的方式显示ViewModel实例。

在DataTemplate中,我有一个Button,它绑定到 MainViewModel命令ItemViewModel类中定义的命令。

<Button Command="{Binding ElementName=mainViewModel,
                          Path=ProcessClickForThisItem}">

所需的行为是按钮调用mainViewModel的命令并告诉其后面的方法,按钮点击来自哪个ItemViewModel实例。

我猜这里可以使用CommandParameter属性。但是,如何引用父视图模型实例?

1 个答案:

答案 0 :(得分:1)

按钮父级将为ListBoxItem,而DataContext将是您感兴趣的ItemViewModel的实例。

您需要RealtiveSource才能获得ListBoxItem。这是您使用CommandParameter的方式:

<Button Command="{Binding ElementName=mainViewModel,
                         Path=ProcessClickForThisItem}"
        CommandParameter="{Binding DataContext,
                              RelativeSource={RelativeSource Mode=FindAncestor, 
                                                   AncestorType=ListBoxItem}}">
相关问题