WPF MenuItem图标共享 [英] WPF MenuItem Icon sharing

查看:85
本文介绍了WPF MenuItem图标共享的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将图标绑定到动态创建这些项目的MenuItem控件.我尝试将x:Shared属性设置为False,但始终只有最后一项具有图标.

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.

这是我的MenuItems ItemContainerStyle代码样式:

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>

以及MenuItem定义:

And the MenuItem definition:

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

我已经尝试在Image控件上设置此Shared属性,但是没有运气.

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

有什么建议吗?

推荐答案

您快到了!

首先:不要被将Icon属性设置为Image控件时,只会创建一个副本.由于控件只能有一个父级,因此每次重新分配它都会从前一个父级中删除.

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.

您有2种解决方案来满足您的需求:

You have 2 solutions for what you want:

  • 改为使用datatemplate,然后重新定义MenuItem的整个模板
  • 使用具有共享图像组件的样式(您尝试实现的目的)

在您的示例中,唯一的错误是Shared属性在Image资源上应该为false,而不是整个样式上.这应该起作用:

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>

希望有帮助.

这篇关于WPF MenuItem图标共享的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆