我正在开发一个完全基于 MVVM 的应用程序。我面临一个绑定(bind)问题。
<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 绑定(bind)在此代码中工作得非常好,但是当涉及到 MenuItem 命令绑定(bind)时,问题就来了。有人可以在这里解释我做错了什么。
最佳答案
在 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>
关于c# - 绑定(bind)中的WPF父子关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17425630/