【问题标题】:WPF: Can use StaticResource only onceWPF:只能使用一次静态资源
【发布时间】:2017-07-17 22:24:16
【问题描述】:

我在 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 设计器在两个按钮上显示图像。

【问题讨论】:

    标签: c# .net wpf xaml


    【解决方案1】:

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

    但是,图像控件(与任何其他 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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-04
      • 1970-01-01
      • 2010-10-25
      • 2013-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多