XAML:如何使用<Image>在"资源"节点中声明的类型资源?



这是我第一次必须将图像用作XAML中的资源。我已经在Window.Resources节点内声明了Image的资源类型,以下方式:

<Window.Resources>
    <Image x:Key="MyIcon" Source="pack://application:,,,/Resources/Images/myicon.png"/>
</Window.Resources>

如何在XAML代码的其他部分中使用此资源?

必须很琐碎,但是我没有找到有关如何使用Image类型资源的任何信息。

显然,使用资源作为Image控件的Source属性不起作用:

        <WrapPanel Background="Transparent" Height="50">
            <Image Source="{StaticResource MyIcon}"/>
        </WrapPanel>

上面的代码在设置Source属性时会引发异常,以下InnerException

{"'System.Windows.Controls.Image' is not a valid value for property 'Source'."}

使用BitmapImage而不是Image作为资源类型:

<Window.Resources>
    <BitmapImage x:Key="MyIcon"
                 UriSource="pack://application:,,,/Resources/Images/myicon.png"/>
</Window.Resources>
...
<WrapPanel Height="50">
    <Image Source="{StaticResource MyIcon}"/>
</WrapPanel>

您也不必在XAML中编写完整的资源文件包URI,因此您可以写下资源声明:

<BitmapImage x:Key="MyIcon" UriSource="/Resources/Images/myicon.png"/>

您可以在WrapPanel内使用ContentControl并重复使用Image资源以前声明的内容:

<WrapPanel Background="Transparent" Height="50">
    <ContentControl Content="{StaticResource MyIcon}" />
</WrapPanel>

最新更新