且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

数据绑定在WPF的父对象

更新时间:2023-01-25 17:58:51

这里要记住的关键是的上下文菜单是不可视树的一部分

The key thing to remember here is context menus are not part of the visual tree.

因此​​,他们不继承相同的源,因为它们属于对绑定的控件。处理这个问题的方法是绑定到文本菜单本身的目标位置。但既然你要绑定它司令部ViewModel类,请将的DataContext在标签您TextBlock的,并在命令中使用绑定这样的 -

Therefore they don't inherit the same source as the control they belong to for binding. The way to deal with this is to bind to the placement target of the ContextMenu itself. But since you want to bind it for Command in ViewModel class, place the DataContext in Tag of your TextBlock and use in your command Binding like this -

<HierarchicalDataTemplate ItemsSource="{Binding Models}">
    <TextBlock Text="{Binding Header}"
               Tag="{Binding DataContext, RelativeSource=
               {RelativeSource Mode=FindAncestor, AncestorType=Window}}">
         <TextBlock.ContextMenu>
              <ContextMenu>
                  <MenuItem Header="Server" Command="{Binding 
                            PlacementTarget.Tag.AddServerCommand,
                            RelativeSource={RelativeSource Mode=FindAncestor, 
                            AncestorType=ContextMenu}}"/>
               </ContextMenu>
          </TextBlock.ContextMenu>
      </TextBlock>
</HierarchicalDataTemplate>

使用其他类似的绑定像上面,它会工作,你想怎样。

Use for other bindings similarly like above and it will work how you want.