假定:
ViewModel中有一个数据源叫Persons,有一个命令叫DoCommand,通过System.Windows.Interactivity触发器绑定鼠标MouseUp事件,当UI端绑定了DataContext数据上下文之后,
Command="{Binding DoCommand}"是找不到这个命令的,必须使用Binging类的RelativeSource属性先找到当前UI,再找到DataContext里面的DoCommand才可以。如下所示
<ListView ItemsSource ="{Binding Persons}">
<ListView.View>
<GridView>
<GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Header="Age" DisplayMemberBinding="{Binding Age}"/>
<GridViewColumn Header="选项">
<GridViewColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="操作">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseUp">
<i:InvokeCommandAction Command="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type local:BindingWindow}},Path=DataContext.DoCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=TextBlock},Path=Text}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBlock>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
关键代码:
Command="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type local:BindingWindow}},Path=DataContext.DoCommand}"
其中,BindingWindow表示当前View窗体的类名。
————————————————
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_37189288/article/details/117415423