这是我的ContextMenu的风格:
<Style x:Key="DIOStyle" TargetType="ContentControl">
<Setter Property="Tag" Value="{Binding Content,RelativeSource={RelativeSource Mode=Self}}"/>
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem Style="{StaticResource DeleteMenuItemStyle}"/>
<!--<MenuItem Header="Normality">
<MenuItem Style="{StaticResource NcMenuItemStyle}"/>
<MenuItem Style="{StaticResource NaMenuItemStyle}"/>
</MenuItem>-->
<MenuItem Style="{StaticResource BothContactsMenuItemStyle}"/>
</ContextMenu>
</Setter.Value>
</Setter>
...
这是我的MenuItem的样式:
<Style x:Key="BothContactsMenuItemStyle" TargetType="MenuItem">
<Setter Property="Header" Value="Both Contacts"/>
<Setter Property="Command" Value="{Binding PlacementTarget.Tag.BothNaNcChangeCommand,RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ContextMenu}}"/>
<Setter Property="Icon">
<Setter.Value>
<Image Style="{StaticResource Tick16Style}" Visibility="{Binding PlacementTarget.Tag.BothNaNc, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ContextMenu}, Converter={StaticResource BoolToVis}}"/>
</Setter.Value>
</Setter>
</Style>
命令绑定正在运行,而图标可见性绑定给我这个错误:
System.Windows.Data错误:4:找不到绑定源 参考'RelativeSource FindAncestor, AncestorType ='System.Windows.Controls.ContextMenu',AncestorLevel ='1''。 BindingExpression:路径= PlacementTarget.Tag.BothNaNc;的DataItem = NULL; target元素是'Image'(Name ='');目标属性是'可见性' (输入“可见性”)
为什么呢? 请注意,这是有效的:
<MenuItem Header="TEST" Visibility="{Binding PlacementTarget.Tag.BothNaNc, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ContextMenu}, Converter={StaticResource BoolToVis}}"/>
答案 0 :(得分:1)
您可以将Image
元素定义为资源。这应该有效:
<Image x:Key="img" x:Shared="False"
Style="{StaticResource Tick16Style}"
Visibility="{Binding PlacementTarget.Tag.BothNaNc, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ContextMenu},
Converter={StaticResource BoolToVis}}"/>
<Style x:Key="BothContactsMenuItemStyle" TargetType="MenuItem">
<Setter Property="Header" Value="Both Contacts"/>
<Setter Property="Command" Value="{Binding PlacementTarget.Tag.BothNaNcChangeCommand, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ContextMenu}}"/>
<Setter Property="Icon" Value="{StaticResource img}" />
</Style>
如果您将Icon
属性设置为您在Image
中内联定义的<Setter.Value>
元素,就像您当前正在执行的那样,它将从父{继承DataContext
{1}}或Window
或定义UserControl
的任何地方。