[C#] WPF - 资源URI

发布于:2025-07-04 ⋅ 阅读:(12) ⋅ 点赞:(0)

一、组成

1、资源URI总共包括4个部分(当前程序集可以省略前3个):

①:pack://application:,,,

②:/[程序集名称]

③:;Component

④:/[资源路径]

二、举例

 项目结构如下图所示:

 1、MainWindow.xaml 文件

<Window
    x: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、预览


网站公告

今日签到

点亮在社区的每一天
去签到