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

标签 wpf xaml button datacontext

我在 WPF 中有 2 个类(class):

  • session
  • 人员

在 session 中我有 2 个 ObservableCollections;包含 People 对象的 AttendingMeetingNotAttendingMeeting

在 xaml 中,DataContext 设置为 Meeting,并且我有 2 个 DataGrid(AttendingMeeting未参加 session )

我需要向每个 DataGrid 添加一个 Button 以便在 Meeting 中添加和删除,但是随后我需要更改Button 上的 DataContext,例如:AttendingMeetingMeeting,以便 Meeting类可以处理在 ObservableCollection 中添加和删除 People

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

最佳答案

假设您尝试从 DataGrid 中绑定(bind)到 Meeting 类上的命令:

您可以在绑定(bind)上使用 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 绑定(bind)到具有您感兴趣的 DataContext 的父级。 relativeSource 太复杂了。

关于wpf - 如何将按钮的DataContext更改为父级DataContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1471643/

相关文章:

c# - IdentityServer3 替代网页浏览器导航事件

c# - WPF Storyboard : DoubleAnimation Works On Opacity But Not TranslateTransform?

c# - WPF 重复密码 IMultiValueConverter

c# - 为什么自定义 ListView 不能拥有自己的 xaml 文件?

windows - 在 Windows 8 (Metro) 应用程序中获取 XAML 控件的 hWnd?

android - 如何将按钮添加到 "extends View"类?

html - 渐变创建伪按钮的问题

c# - WPF 获取特定坐标处的元素

c# - 在IOS上设置背景

javascript - jQuery:为什么不在生成的按钮上调用点击功能