WPF应用加载图片URI指定需要注意的地方

应用程序(.exe)加载图片:

可以省略"pack://application:,,," 打头,因为系统运行时需要的图片文件在Exe程序集(组合体)中;譬如:

<Image Source="/ClinicalManagement.CPOE;component/Resources/Expand.png" Stretch="None" />

动态链接库(.dll)加载图片:

然而如果图片文件在另一个DLL文件中,系统运行加载图片资源如果省略pack:就默认找本地程序集(Exe文件)就会找不到。就必须如下:

<local:FadableToggleButton x:Name="_fadableToggle" DockPanel.Dock="Right" VerticalAlignment="Top" Padding="5,0,0,0"
    Visibility="{Binding RelativeSource={RelativeSource AncestorType=cui:CascadingListBoxItem,Mode=FindAncestor,AncestorLevel=1},Path=IsMouseOver,Converter={x:Static js:Converters.BooleanToVisibility},ConverterParameter={x:Static Visibility.Hidden}}">
    <local:FadableToggleButton.Content>
        <Image Source="pack://application:,,,/ClinicalManagement.CPOE;component/Resources/Expand.png" Stretch="None" />
    </local:FadableToggleButton.Content>
    <local:FadableToggleButton.CheckedContent>
        <Image Source="pack://application:,,,/ClinicalManagement.CPOE;component/Resources/Collapse.png" Stretch="None" />
    </local:FadableToggleButton.CheckedContent>
</local:FadableToggleButton>

另外:添加到项目中的图片文件需要设置为“不复制”, “Resource”

资料:

WPF引入了统一资源标识Uri(Unified Resource Identifier)来标识和访问资源。其中较为常见的情况是用Uri加载图像。Uri表达式的一般形式为:协议+授权+路径 协议:pack:// 授权:有两种。一种用于访问编译时已经知道的文件,用application:///。一种用于访问编译时不知道、运行时才知道的文件,用siteoforigin:///。在这里加
  

  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);

原文地址:https://www.cnblogs.com/chriskwok/p/3196009.html