我在自定义控件中找不到 ContextMenu 菜单项的正确绑定(bind)。
<ContextMenu x:Key="MyContextMenu">
<MenuItem Header="MyMenuItem"
Command="{Binding PlacementTarget.MyCommand, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}"/>
</ContextMenu>
<Style TargetType="{x:Type local:MyControl}" x:Shared="False">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:MyControl}">
<DockPanel ContextMenu="{StaticResource MyContextMenu}">
<!--some controls-->
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
MyCommand 在 MyControl.xaml.cs 中定义,是我希望绑定(bind)到菜单项的命令。
示例中的绑定(bind)在 DockPanel 中查找 MyCommand。什么是正确的绑定(bind)?
最佳答案
您需要将标签添加到菜单的容器并使用放置目标绑定(bind)到它。
查看此示例:
<StackPanel x:Key="ConfigurationListItem" x:Shared="False" Tag="{Binding ElementName=UserControl}">
<StackPanel.ContextMenu>
<ContextMenu DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}" Tag="{Binding}">
<MenuItem Header="Sync Environment Dependencies"
Command="{Binding Parent.PlacementTarget.Tag.SyncEnvironmentCommand, RelativeSource={RelativeSource Self}}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}, Path=PlacementTarget.DataContext}" />
</ContextMenu>
</StackPanel.ContextMenu>
</StackPanel>
关于wpf - 自定义控件中 ContextMenu 的正确绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29150230/