一、組成
1、資源URI總共包括4個部分(當前程序集可以省略前3個):
①:pack://application:,,,
②:/[程序集名稱]
③:;Component
④:/[資源路徑]
二、舉例
?項目結構如下圖所示:
?1、MainWindow.xaml 文件
<Windowx:Class="WpfApp1.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"Title="MainWindow"Width="800"Height="600"mc:Ignorable="d"><Window.Resources><Style TargetType="Image"><Setter Property="Width" Value="200" /></Style></Window.Resources><UniformGrid Columns="3"><!-- 絕對路徑 --><Image Source="pack://application:,,,/WpfApp1;Component/Assets/monkey.png" /><!-- 相對路徑 --><Image Source="/WpfApp1;Component/Assets/monkey.png" /><!-- 相對路徑:當前程序集 --><Image Source="/Assets/monkey.png" /><!-- 后臺設置 --><Image x:Name="image1" /><Image x:Name="image2" /><Image x:Name="image3" /></UniformGrid>
</Window>
?2、MainWindow.xaml.cs 文件
using System.Windows;
using System.Windows.Media.Imaging;namespace WpfApp1
{public partial class MainWindow : Window{public MainWindow(){InitializeComponent();image1.Source = new BitmapImage(new System.Uri("pack://application:,,,/WpfApp1;Component/Assets/monkey.png", System.UriKind.Absolute));image2.Source = new BitmapImage(new System.Uri("/WpfApp1;Component/Assets/monkey.png", System.UriKind.Relative));image3.Source = new BitmapImage(new System.Uri("/Assets/monkey.png", System.UriKind.Relative));}}
}
3、預覽