WPF MenuItem图标共享

编程入门 行业动态 更新时间:2024-10-08 19:40:40
本文介绍了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图标共享

本文发布于:2023-11-13 03:04:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1583249.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:图标   WPF   MenuItem

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!