【问题标题】:How to change the DataContext of a button to the parents parent DataContext?如何将按钮的 DataContext 更改为父级父 DataContext?
【发布时间】:2010-12-01 02:16:27
【问题描述】:

我在 WPF 中有 2 个类:

  • 会议

在会议中我有 2 个ObservableCollectionsAttendingMeetingNotAttendingMeeting 包含 People 对象

在 xaml 中,DataContext 设置为 Meeting,我有 2 个 DataGrids(AttendingMeetingNotAttendingMeeting

我需要在每个DataGrids 中添加一个Button 以从Meeting 添加和删除,但是我需要将Button 上的DataContext 从例如:AttendingMeeting 更改为Meeting,以便Meeting 类可以处理PeopleObservableCollections 中添加和删除。

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

【问题讨论】:

    标签: wpf xaml button datacontext


    【解决方案1】:

    假设您尝试从DataGrid 中绑定到会议类上的命令:

    您可以在绑定上使用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 绑定到具有您感兴趣的DataContext 的父级。

    【讨论】:

    • 感谢您指导我找到解决方案。这是我的工作命令绑定:Command="{Binding ElementName=SelectedMeeting, Path=DataContext.AddPatientsToMeetingCommand}" CommandParameter="{Binding}"
    • 我个人更喜欢使用 ElementName 而不是爬树寻找祖先。这可以直接引用您要使用的元素,而不是依赖于结构不会以影响爬树的方式进行更改(在两者之间的某个点添加另一个网格)。
    • 很高兴能帮上忙。 @bambuska,我同意...爬树绝对不是最好的方法,尤其是在寻找像网格这样常见的东西时。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-09
    • 1970-01-01
    • 2013-02-02
    • 2016-04-30
    • 2021-12-21
    相关资源
    最近更新 更多