当菜单打开时,XAML ResourceDictionary 中的图像在工具栏上消失 [英] Images in XAML ResourceDictionary disappear on ToolBar when Menu opens
问题描述
我已经开始将各种常见的 Image
移动到 ResourceDictionary
中,并注意到我的 WPF 应用程序中有一个奇怪的行为.如果 Image
用于 MenuItem
和 Button
上的 ToolBar
,当我打开 Menu
图像消失在 Button
上.
I have started to move various common Image
s into a ResourceDictionary
and noticed an odd behavior in my WPF application. If the Image
is used in a MenuItem
and in a Button
on a ToolBar
, when I open the Menu
the image disappears on the Button
.
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Image x:Key="NewImage"
Source="/SomeApplication;component/Resources/NewDocumentHS.png"
Stretch="None"/>
<!-- ... -->
来自Window
的相关XAML:
<Menu>
<MenuItem Header="_File">
<MenuItem Header="_New"
Command="{Binding NewCommand}"
Icon="{DynamicResource NewImage}" />
<!-- ... -->
<ToolBarTray>
<ToolBar>
<Button Command="{Binding NewCommand}"
Content="{DynamicResource NewImage}" />
我认为这是对 ResourceDictionary
中资源的警告,但我无法找到相应的修复方法.StaticResource
和 DynamicResource
都会发生行为.它似乎也不受 ResourceDictionary
独立或与其他人合并的影响.也没有其他资源共享该密钥.
I assume this is a caveat of resources in a ResourceDictionary
, but I am unable to discover the appropriate fix for this. Behavior occurs with both StaticResource
and DynamicResource
. It also doesn't appear to be affected by if the ResourceDictionary
stands on its own or if it is merged with others. No other resource shares that key either.
编辑:此外,将 PresentationOptions:Freeze="True"
添加到图像并没有改变这种情况.
Edit: Additionally, adding PresentationOptions:Freeze="True"
to the images did not change the situation.
推荐答案
Image 类是一个视觉对象,因此它只能出现在视觉对象树中的一个位置.因此,您不能在多个 MenuItems/Buttons/etc 之间共享它.
The Image class is a visual, so it can only appear in the visual tree in one location. Therefore, you cannot share it among multiple MenuItems/Buttons/etc.
不过,您可以共享 ImageSource(即 Image.Source)值.
You can however share the ImageSource (i.e. Image.Source) value.
在 WPF 中,我相信您可以使用 x:Shared=False"强制 WPF 为每个请求创建一个新实例.
In WPF, I believe you can use x:Shared="False" to force WPF to create a new instance for each request though.
这篇关于当菜单打开时,XAML ResourceDictionary 中的图像在工具栏上消失的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!