我想将图标绑定到动态创建这些项目的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图标共享
发布评论