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

时间:2009-09-24 13:17:35

标签: wpf xaml button datacontext

我在WPF中有两个类:

  • 会议

在开会中我有2 ObservableCollections;包含AttendingMeeting个对象的NotAttendingMeetingPeople

在xaml中,DataContext设置为Meeting,我有2 DataGrid s(AttendingMeetingNotAttendingMeeting

我需要为每个Button添加DataGrid来添加和删除Meeting,但我需要更改DataContext Button 1}}从例如:AttendingMeetingMeeting,以便Meeting类可以处理从People添加和删除ObservableCollection

如何在xaml中执行此操作(将DataContextAttendingMeeting项更改为父项parent-> Meeting)?

1 个答案:

答案 0 :(得分:3)

假设您正尝试从DataGrid中绑定到Meeting类上的Command:

您可以在绑定上使用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>

如果您处理大量嵌套而ElementName过于复杂,您还可以使用DataContext绑定到您感兴趣的RelativeSource的父级。