我已经开始将各种常见的Image
移到ResourceDictionary
中,并且注意到我的WPF应用程序中的行为异常。如果在Image
和MenuItem
的Button
中使用了ToolBar
,则当我打开Menu
时,图像会在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
是独立存在的还是与其他人合并的,似乎也不会受到影响。也没有其他资源共享该 key 。编辑:此外,向图像添加
PresentationOptions:Freeze="True"
不会改变这种情况。
最佳答案
Image类是一种视觉,因此它只能出现在视觉树中的一个位置。因此,您不能在多个MenuItems/Buttons/etc之间共享它。
不过,您可以共享ImageSource(即Image.Source)值。
在WPF中,我相信您可以使用x:Shared =“False”强制WPF为每个请求创建一个新实例。
关于wpf - 菜单打开时,XAML ResourceDictionary中的图像在工具栏上消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5597554/