如何将按钮的DataContext更改为其父级的父级DataContext?

3

我在WPF中有两个类:

  • 会议(Meeting)
  • 人员(People)

在会议(Meeting)类中,我有两个ObservableCollections:AttendingMeeting和NotAttendingMeeting,它们包含People对象。

在XAML中,DataContext设置为Meeting,并且我有两个DataGrids(AttendingMeeting和NotAttendingMeeting)。

我需要为每个DataGrid添加一个按钮来添加和删除Meeting中的People。但是我需要更改Button上的DataContext,例如:从AttendingMeeting更改为Meeting,以便Meeting类可以处理从ObservableCollections添加和删除People。

如何在XAML中实现这一点(将DataContext从AttendingMeeting更改为其父级parent-> Meeting)?

1个回答

4
假设您想从DataGrid中绑定到Meeting类上的命令:
您可以在绑定中使用RelativeSource来获取您感兴趣的DataContext。您的标记可能类似于此:
<Grid DataContext="..."> <!-- Assuming a grid is you're layout root and that it's datacontext is the Meeting you spoke of -->
   ...
   <DataGrid ...>
      ...

      <Button Content="Click Me!"
              Command="{Binding Path="DataContext.RemovePersonCommand"
                                RelativeSource={RelativeSource FindAncestor,
                                                AncestorType={x:Type Grid}}}"
              CommandParameter="{Binding}"/> <!-- This would be binding to the current person -->
      ...
   </DataGrid>
   ...
</Grid>

如果你需要处理大量的嵌套并且使用RelativeSource会过于复杂,你也可以使用ElementName绑定到一个包含所需数据上下文的父元素。


1
感谢您引导我找到解决方案。这是我的工作命令绑定:Command="{Binding ElementName=SelectedMeeting, Path=DataContext.AddPatientsToMeetingCommand}" CommandParameter="{Binding}" - code-zoop
1
个人而言,我更喜欢使用ElementName而不是沿着树向上查找祖先。这样可以直接引用您想要使用的元素,而不是依赖于结构不会以影响您的树遍历方式改变的方式(在某些时候添加另一个网格)。 - stiank81
1
很高兴能够帮助。@bambuska,我同意...攀爬树木绝对不是最好的方法,特别是当寻找像网格这样常见的东西时。 - dustyburwell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接