WPF之Uri加载图片

     WPF引入了统一资源标识Uri(Unified Resource Identifier)来标识和访问资源。其中较为常见的情况是用Uri加载图像。Uri表达式的一般形式为:协议+授权+路径
     协议pack://
     授权:有两种。一种用于访问编译时已经知道的文件,用application:///。一种用于访问编译时不知道、运行时才知道的文件,用siteoforigin:///。在这里加载图片时,我们选用前者,即application:///,但是书写时候,我们一般用逗号代替斜杠,也就是改写作application:,,,
     路径:分为绝对路径和相对路径。这里我们选用相对路径,普适性更强。

     下面,我们举一个简单的例子:
          pack://application:,,,/images/my.jpg
     当然,WPF默认Uri设置有pack://application:,,,,所以我们也可以直接将其写作:
          /images/my.jpg
     后边写例子程序时,为了让读者更好的了解Uri,我们都采用完整的Uri写法。

     下面在讲讲装载图片的两种方式,一种用XAML引用资源,一种用代码引用资源。

     用XAML引用资源:
          <Image Source="pack://application:,,,/images/my.jpg"/>

     用代码引用资源:
          Image img;
          img.Source=new BitmapImage(new Uri("pack://application:,,,/images/my.jpg"),UriKind.Relative);


     我们写一个例子代码。在其中运用XAML,代码两种方式引用资源。

Window1.xaml

<Window x:Class="testURI.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="400" Width="240">
    <!--堆积面板是最简单的控制面板-->
    <StackPanel>
        <!--1.XAML中引用图片资源-->
        <!--也可用Image Name="image1" Source="pack://application:,,,/images/1.jpg" Height="165" Width="220"/-->
        <Image Name="image1" Source="pack://application:,,,/images/1.jpg" Height="165" Width="220"/>
        
        <!--定义Image对象,但是没有指定图片源,待在代码中指定Source源-->
        <Image Name="image2" Height="165" Width="220"/>
    </StackPanel>
</Window>

 Window1.xaml.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace testURI
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            //2.代码中引用图片资源  
            image2.Source = new BitmapImage(new Uri("/images/2.jpg", UriKind.Relative));
        }
    }
}

文档结构:

最终实现截图如下:=========

原文地址:https://www.cnblogs.com/ErinCodeMM/p/2008819.html