WPF 中图片的加载 ,使用统一资源标识符 (URI)

 

在wpf中,设置图片路径有2种方法:

1、xaml文件中,指定路径

 <Button Name="button_set" Click="button_set_Click" Focusable="False" Margin="0,50,50,0" Width="36" Height="36" HorizontalAlignment="Right" VerticalAlignment="Top" >
     <Button.Background>
           <ImageBrush ImageSource="pack://application:,,,/Images/icon_setting_off.png" Stretch="Fill"/>
     </Button.Background>
 </Button>

<Image Margin="310,0,0,0" Width="25" Height="25" HorizontalAlignment="Left" VerticalAlignment="Stretch"

   Source="pack://application:,,,/Images/moon.png"/>

 

2、后台代码设置路径

ImageBrush b = new ImageBrush();
b.ImageSource = new BitmapImage(new Uri("pack://application:,,,/Themes/ZCThemes/skin/icon/card_choosed.png", UriKind.RelativeOrAbsolute));
b.Stretch = Stretch.Fill;
SelectToAddEvent.Background = b;


image.Source = new BitmapImage(new Uri("pack://application:,,,/Images/haha.jpg"));
//或
image.Source = new BitmapImage(new Uri("pack://SiteOfOrigin:,,,/Images/haha.jpg"));

 

WPF 引入了统一资源标识 Uri (Unified Resource Identifier) 来标识和访问资源。

Uri 表达式的一般形式为:协议+授权+路径

  协议:pack://
  授权:有两种。一种用于访问编译时已经知道的文件,用  application:///  一种用于访问编译时不知道、运行时才知道的文件,用 siteoforigin:///
      一般用逗号代替斜杠,也就是改写作application:,,,和pack:,,,
  路径:分为绝对路径和相对路径。一般选用相对路径,普适性更强


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

用XAML引用资源:

<Image Source="pack://application:,,,/images/my.jpg"/>

 < Image Source = "/images/my.jpg" />

 

用后台代码引用资源:

Image img;
img.Source=new BitmapImage(new Uri("pack://application:,,,/images/my.jpg"),UriKind.Relative);

 image2.Source = new BitmapImage(new Uri("/images/my.jpg", UriKind.Relative));

 

使用SiteOfOrigin时   

imgContent.Source = new BitmapImage(new Uri("pack://SiteOfOrigin:,,,/images/my.jpg"));

 

 

 
posted @ 2019-04-10 01:13  唐宏昌  阅读(547)  评论(1编辑  收藏  举报