How to override ContextMenu in global style?

2019-09-13 20:50发布

问题:

I declare the style of my control in library:

<ContentControl.Resources>
    <ContextMenu x:Key="ContextMenu">
        <MenuItem Header="{x:Static Drawing:Headers.AddEdge}"  Click="AddEdgeClick"/>
        <MenuItem Header="{x:Static Drawing:Headers.ChangeID}" Click="ChangeIDClick"/>
        <MenuItem Header="{x:Static Drawing:Headers.Remove}"   Click="RemoveClick"/>
    </ContextMenu>
    <Style x:Key="Style" TargetType="{x:Type Drawing:Node}">
        <Setter Property="ContextMenu" Value="{StaticResource ContextMenu}"/>
    </Style>
</ContentControl.Resources>

<ContentControl.Style>
    <StaticResource ResourceKey="Style"/>
</ContentControl.Style>

But global style for this control in application doesn't work...

<Style TargetType="Drawing:Node">
    <Setter Property="ContextMenu" Value="{x:Null}"/>
    <EventSetter Event="MouseLeftButtonUp" Handler="DirectoryClicked"/>
</Style>

回答1:

If you explicitly set the Style property on an element, then any implicit Styles (i.e. your global style) will not be applied. If your global style is actually the default Style, then it should still be applied, but it doesn't sounds like what you are doing.

You can base your explicit Style on your implicit Style though, like so:

<Style x:Key="Style" TargetType="{x:Type Drawing:Node}" BasedOn="{StaticResource {x:Type Drawing:Node}}">
    <Setter Property="ContextMenu" Value="{StaticResource ContextMenu}"/>
</Style>

This is of course assuming that Drawing:Node is the same class/type as GraphNode:Node.