这是我第一次必须将图像用作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>