wpf - 自定义控件中 ContextMenu 的正确绑定(bind)

标签 wpf binding contextmenu

我在自定义控件中找不到 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/

相关文章:

.net - 如何检测由于 Windows 7 幻灯片放映而导致的墙纸变化?

wpf - 鼠标悬停在图像控件上时显示弹出窗口

ubuntu - 如何将 key 绑定(bind)到ubuntu中的另一个 key ?

xaml - 绑定(bind)到 Xaml

vba - 如何在自定义 Office 功能区中拥有多个上下文菜单

apache-flex - Flex4 ContextMenu() 不显示添加的项目

android - 如何从 contextMenu 访问 ListItem 位置

c# - 应用程序对象正在关闭异常

c# - WPF Datagrid 排序索引问题

angularjs - 在 AngularJS 中保持动态表与模型同步