這是我的文本菜單樣式:WPF文本菜單:菜單項圖標的可視性綁定錯誤
<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>
...
,這是我的菜單項的樣式:
<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 Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.ContextMenu', AncestorLevel='1''. BindingExpression:Path=PlacementTarget.Tag.BothNaNc; DataItem=null; target element is 'Image' (Name=''); target property is 'Visibility' (type 'Visibility')
爲什麼? 請注意,這是工作:
<MenuItem Header="TEST" Visibility="{Binding PlacementTarget.Tag.BothNaNc, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=ContextMenu}, Converter={StaticResource BoolToVis}}"/>