WPF菜单项不会关闭

时间:2015-07-27 13:34:01

标签: c# wpf xaml

我想用以下样式重新设置ContextMenu的样式

   <ControlTemplate x:Key="{x:Static MenuItem.SubmenuItemTemplateKey}" TargetType="MenuItem">
    <Border x:Name="templateRoot" BorderBrush="{TemplateBinding BorderBrush}"
            BorderThickness="{TemplateBinding BorderThickness}" 
            Background="{TemplateBinding Background}" Height="22" SnapsToDevicePixels="true">
        <Grid>
           <Button>
                <ContentPresenter 
                        Name="HeaderHost"
                        ContentSource="Header"
                        RecognizesAccessKey="True"/>
            </Button>
        </Grid>
    </Border>
    <ControlTemplate.Triggers>
        <Trigger Property="IsHighlighted" Value="True">
            <Setter Property="Background" TargetName="templateRoot" Value="Transparent"/>
            <Setter Property="BorderBrush" TargetName="templateRoot" Value="{StaticResource MenuItem.Highlight.Border}"/>
        </Trigger>
        <Trigger Property="IsEnabled" Value="false">
            <Setter Property="Foreground" Value="{StaticResource DisabledForegroundBrush}"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

点击我的上下文菜单项后,它会触发我的回叫,但菜单本身会停留在屏幕上。如何触发关闭逻辑?

由于

1 个答案:

答案 0 :(得分:2)

Button正在处理点击事件并阻止它将可视树冒泡到MenuItem

在按钮上设置IsHitTestVisible会停止Button处理点击事件,但也会停止MouseOver/Pressed样式设置。

<Button IsHitTestVisible="False">
    <ContentPresenter 
    Name="HeaderHost"
    ContentSource="Header"
    RecognizesAccessKey="True"/>
</Button>