WPF MenuItem Icon sharing

纵然是瞬间 提交于 2020-08-20 04:30:29

问题


I want to bind icons to the MenuItem controls where these items are dynamically created. I tried to set the x:Shared attribute to False but always only the last item has icon.

Here is my style for the MenuItems ItemContainerStyle code:

<Window.Resources>
    <Style TargetType="{x:Type MenuItem}" x:Key="MenuItemStyle" x:Shared="False">
        <Setter Property="Icon">
            <Setter.Value>
                <Image Source="{Binding IconSource}" />
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>

And the MenuItem definition:

<MenuItem Header="Workspaces" ItemsSource="{Binding WorkspaceItems}" Icon="{StaticResource BranchIcon}" ItemContainerStyle="{StaticResource MenuItemStyle}" />

I have already tried to set this Shared attribute on the Image control but no luck.

Any suggestion?


回答1:


You are almost there!

First of all: don't be confuse by Template vs Style.

When you are setting Icon property to an Image control, only one copy is created. As a control can have only one parent, it is removed from the previous parent each time it's re-assigned.

That's why you see only one icon.

You have 2 solutions for what you want:

  • use datatemplate instead, and redefine the whole Template of a MenuItem
  • use a style with a shared image component (what you tried to achieve)

In your example the only error is that the Shared attribute should be false on the Image resource, not on the whole style. This should work:

<Window.Resources>
    <Image x:Key="MenuIconImage" x:Shared="false" Source="{Binding IconSource}"/>

    <Style TargetType="{x:Type MenuItem}" x:Key="MenuItemStyle" BasedOn="{StaticResource {x:Type MenuItem}}">
        <Setter Property="Icon" Value="{StaticResource MenuIconImage}">
        </Setter>
    </Style>
</Window.Resources>

Hope it helps.



来源:https://stackoverflow.com/questions/40038759/wpf-menuitem-icon-sharing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!