WPF:仅能使用StaticResource一次

9

我在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>

但它只在最后一个按钮上显示为按钮图像。第一个按钮没有图像。

当我移除第二个按钮时,它可以用于第一个按钮。如何多次使用StaticResource?Visual Studio GUI设计器在两个按钮上都显示图像。

1个回答

19

默认情况下,XAML资源是共享的,这意味着只有一个实例在XAML中被引用时被重复使用。

然而,Image控件(与任何其他UI元素一样)只能有一个父控件,因此不能共享。

您可以将x:Shared属性设置为false:

<Image x:Key="MyImage" x:Shared="false" Source="../Icons/img.png" Width="16" Height="16"/>

通常不将UI元素用作资源。替代方案是使用BitmapImage资源,如下所示:


<Window.Resources>
    <BitmapImage x:Key="MyImage" UriSource="../Icons/img.png"/>
</Window.Resources>

<Button>
    <Image Source="{StaticResource MyImage}" Width="16" Height="16"/>
</Button>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接