[C#] WPF - 资源URI

一、组成

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

①:pack://application:,,,

②:/[程序集名称]

③:;Component

④:/[资源路径]

二、举例

项目结构如下图所示:

1、MainWindow.xaml 文件

html 复制代码
<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 文件

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、预览

相关推荐
A_nanda11 小时前
c# MOdbus rto读写串口,如何不相互影响
算法·c#·多线程
码云数智-园园13 小时前
使用 C# 将 PowerPoint 演示文稿高效转换为 PDF 格式
c#
听麟13 小时前
HarmonyOS 6.0+ 智慧出行导航APP开发实战:离线地图与多设备位置协同落地
华为·wpf·harmonyos
PfCoder14 小时前
WinForm真入门(23)---PictureBox 控件详细用法
开发语言·windows·c#·winform
gc_229916 小时前
C#学习调用OpenMcdf模块解析ole数据的基本用法(1)
c#·ole·openmcdf
MM_MS21 小时前
Halcon图像点运算、获取直方图、直方图均衡化
图像处理·人工智能·算法·目标检测·计算机视觉·c#·视觉检测
笨蛋不要掉眼泪21 小时前
Spring Boot + RedisTemplate 数据结构的基础操作
java·数据结构·spring boot·redis·wpf
老骥伏枥~1 天前
C# 控制台:Console.ReadLine / WriteLine
开发语言·c#
PfCoder1 天前
C#中定时器之System.Timers.Timer
c#·.net·visual studio·winform