覆盖 MenuItem ControlTemplate 可防止在单击项目时关闭 ContextMenu

Overriding MenuItem ControlTemplate prevents the ContextMenu from closing when an item is clicked

我正在使用 WPF 并像这样覆盖 MenuItemControlTemplate

<Button Content="Click Me" Margin="5">
    <Button.ContextMenu>
        <ContextMenu>
            <MenuItem>
                <MenuItem.Template>
                    <ControlTemplate>
                        <Button Padding="0" BorderThickness="0" Background="Transparent" HorizontalAlignment="Left"
                                Command="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=DataContext.MenuItemCommand}">
                            <TextBlock Text="Item 1" Margin="5"/>
                        </Button>
                    </ControlTemplate>
                </MenuItem.Template>
            </MenuItem>
        </ContextMenu>
    </Button.ContextMenu>
</Button>

我的上下文菜单打开得很好,当我单击该项目时,它会很好地激活按钮的命令,但上下文菜单不会关闭。关于在单击某个项目后我需要做什么才能关闭上下文菜单有什么建议吗?

从模板中删除 Button 并处理 MenuItem 本身的 Command:

<Button Content="Click Me" Margin="5">
    <Button.ContextMenu>
        <ContextMenu>
            <MenuItem Command="{Binding MenuItemCommand}">
                <MenuItem.Template>
                    <ControlTemplate>
                        <TextBlock Text="Item 1" Margin="5"/>
                    </ControlTemplate>
                </MenuItem.Template>
            </MenuItem>
        </ContextMenu>
    </Button.ContextMenu>
</Button>

要隐藏 MenuItem 的默认背景,您可以设置如下样式:

<Button Content="Click Me" Margin="5">
    <Button.ContextMenu>
        <ContextMenu>
            <ContextMenu.Resources>
                <Style TargetType="{x:Type MenuItem}">
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate>
                                <Border Name="bdr" Margin="-5" Padding="10" Background="White">
                                    <TextBlock Text="{Binding RelativeSource={RelativeSource Mode=TemplatedParent},Path=Header}"/>
                                </Border>
                                <ControlTemplate.Triggers>
                                    <Trigger Property="IsMouseOver"  Value="True">
                                        <Setter Property="Background" TargetName="bdr" Value="AliceBlue"/>
                                    </Trigger>
                                </ControlTemplate.Triggers>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ContextMenu.Resources>
            <MenuItem Header="Item 1" Command="{Binding RelativeSource={RelativeSource AncestorType=ContextMenu}, Path=DataContext.MenuItemCommand}"/>
        </ContextMenu>
    </Button.ContextMenu>
</Button>