2017-03-03 74 views
1

這是我的文本菜單樣式: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}}"/> 

回答

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屬性設置爲您在<Setter.Value>定義內嵌像你正在做的Image元素,它會繼承父WindowUserControl或地方的Style定義的DataContext