2016-06-11 82 views
1

我有這樣的XAML從我的視圖模型渲染菜單:菜單項的圖標在WPF菜單消失

<DockPanel> 
    <Menu DockPanel.Dock="Top" ItemsSource="{Binding MenuItems}"> 
     <Menu.Resources> 
      <SolidColorBrush x:Key="ImageBrush" Color="Blue"/> 

      <HierarchicalDataTemplate DataType="{x:Type local:MenuItemViewModel}" ItemsSource="{Binding Path=ChildMenuItems}"> 
       <HierarchicalDataTemplate.ItemContainerStyle> 
        <Style TargetType="MenuItem"> 
         <Setter Property="Command" Value="{Binding Command}" /> 
         <Setter Property="Icon"> 
          <Setter.Value> 
           <Image Source="{Binding Path=Icon, Converter={fa:ImageSourceConverter}, ConverterParameter={StaticResource ImageBrush}}" /> 
          </Setter.Value> 
         </Setter> 
        </Style> 
       </HierarchicalDataTemplate.ItemContainerStyle> 
       <StackPanel Orientation="Horizontal"> 
        <Label Content="{Binding Header}" /> 
       </StackPanel> 
      </HierarchicalDataTemplate> 
     </Menu.Resources> 
    </Menu> 
</DockPanel> 

所有作品,除了圖標第一個菜單打開後消失的罰款。假設我有兩個菜單,每個菜單都有一個子菜單,我打開菜單'A',子菜單顯示圖標。然後我打開菜單'B',子菜單顯示圖標。然後再次打開菜單'A',子菜單不顯示圖標。菜單'B'中只有子菜單顯示它的圖標。

回答

2

Image是一個Control它只能有一個父母,所以你會看到這種行爲。創建資源並設置Image控制與x:Shared XAML屬性的非共享:

<Menu DockPanel.Dock="Top" ItemsSource="{Binding MenuItems}"> 
      <Menu.Resources> 
       <SolidColorBrush x:Key="ImageBrush" Color="Blue"/> 
       <Image x:Key="menuIcon" x:Shared="false" Source="{Binding Path=Icon, Converter={fa:ImageSourceConverter}, ConverterParameter={StaticResource ImageBrush}}" /> 
       <HierarchicalDataTemplate DataType="{x:Type local:MenuItemViewModel}" ItemsSource="{Binding Path=ChildMenuItems}"> 
        <HierarchicalDataTemplate.ItemContainerStyle> 
         <Style TargetType="MenuItem"> 
          <Setter Property="Command" Value="{Binding Command}" /> 
          <Setter Property="Icon" Value="{StaticResource menuIcon}" /> 
         </Style> 
        </HierarchicalDataTemplate.ItemContainerStyle> 
        <StackPanel Orientation="Horizontal"> 
         <Label Content="{Binding Header}" /> 
        </StackPanel> 
       </HierarchicalDataTemplate> 
      </Menu.Resources> 
     </Menu> 

檢查我的樣本here

+0

陳:謝謝你,問題解決了! – Andreas

+0

@Andreas歡迎:) –