简体   繁体   English

WPF绑定中的父子关系

[英]WPF parent child relation in binding

I am working on an application which is totally based on MVVM. 我正在开发一个完全基于MVVM的应用程序。 I am facing a binding problem. 我面临一个有约束力的问题。

<ListView ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}},Path=DataContext.CurrentSecurityList}">
<ListView.ContextMenu>
 <ContextMenu>
  <MenuItem Header="Remove" Command="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type UserControl}},Path=DataContext.RemoveSecurity}"/>
 </ContextMenu>
</ListView.ContextMenu> 

ListView binding is working absolutely fine in this code but the problem comes when it comes to MenuItem Command Binding. ListView绑定在此代码中绝对可以正常工作,但在涉及MenuItem Command Binding时出现问题。 Can someone explain what i am doing wrong over here. 有人可以解释我在这里做错了什么。

ContextMenu works on different visual tree so it is not possible to bind it like that. ContextMenu在不同的视觉树上工作,因此无法像这样绑定它。 You need to find ContextMenu ancestor and refer to its PlacementTarget.DataContext to retrieve your command. 您需要找到ContextMenu祖先,并参考其PlacementTarget.DataContext来检索命令。 Try something like this: 尝试这样的事情:

<MenuItem Header="Remove" Command="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type ContextMenu}},Path=PlacementTarget.DataContext.RemoveSecurity}"/>

Put a Tag in ListView to connect its ancestor to its ContextMenu: 在ListView中放置一个Tag,以将其祖先连接到其ContextMenu:

<ListView ItemsSource="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}},Path=DataContext.CurrentSecurityList}"
              Tag="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}">
        <ListView.ContextMenu>
            <ContextMenu>
                <MenuItem Header="Remove" Command="{Binding PlacementTarget.Tag.DataContext.RemoveSecurity, RelativeSource={RelativeSource 
                                AncestorType=ContextMenu}}"/>
            </ContextMenu>
        </ListView.ContextMenu>
    </ListView>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM