WPF:只能使用一次StaticResource [英] WPF: Can use StaticResource only once
问题描述
我在WPF Windows XAML中定义了一个静态资源:
I have a Static resource defined in my WPF Windows XAML:
<Window.Resources>
<Image x:Key="MyImage" Source="../Icons/img.png" Width="16" Height="16" Stretch="None" />
</Window.Resources>
我要两次使用它:
<Grid>
<Button Content="{StaticResource MyImage}" RenderOptions.BitmapScalingMode="NearestNeighbor" RenderOptions.EdgeMode="Aliased" />
</Grid>
...
<Grid>
<Button Content="{StaticResource MyImage}" RenderOptions.BitmapScalingMode="NearestNeighbor" RenderOptions.EdgeMode="Aliased" />
</Grid>
但是它只能显示为按钮图像一次。在最后一个按钮上。第一个按钮没有图像。
But it gets displayed as button image only once. On the last button. The first button has no image.
当我删除第二个按钮时,它对第一个按钮有效。如何多次使用StaticResource? Visual Studio GUI设计器在两个按钮上都显示图像。
When I remove the second button then it works for the first one. How to use the StaticResource multiple times? The Visual Studio GUI Designer displays the images on both buttons.
推荐答案
默认情况下,XAML资源是共享的,这意味着仅
By default, XAML resources are shared, which means there is only one instance that is reused as often as it is referenced in XAML.
但是,一个Image控件(与其他UI元素一样)只能有一个父控件,因此可以重复使用XAML中引用的实例。
However, an Image control (as any other UI element) can only have one parent control, so can't be shared.
您可以将 x:Shared
属性设置为false:
You can set the x:Shared
attribute to false:
<Image x:Key="MyImage" x:Shared="false" Source="../Icons/img.png" Width="16" Height="16"/>
您通常不将UI元素用作资源。另一种选择是这样的BitmapImage资源:
You typically don't use UI elements as resources. An alternative would be a BitmapImage resource like this:
<Window.Resources>
<BitmapImage x:Key="MyImage" UriSource="../Icons/img.png"/>
</Window.Resources>
<Button>
<Image Source="{StaticResource MyImage}" Width="16" Height="16"/>
</Button>
这篇关于WPF:只能使用一次StaticResource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!