C# 字符串中的ImageSource不工作?
我在项目的文件夹中有一堆*.tif图像。我还将这些图像添加到位于“模板\团队徽标”文件夹中的visual studio项目中 现在,如果我将图像源设置为:C# 字符串中的ImageSource不工作?,c#,wpf,image,imagesource,C#,Wpf,Image,Imagesource,我在项目的文件夹中有一堆*.tif图像。我还将这些图像添加到位于“模板\团队徽标”文件夹中的visual studio项目中 现在,如果我将图像源设置为: <Image Name="UL_Team1_Image" Grid.Row="1" Grid.Column="1" Margin="5" Source="Team Logos\ARI.tif"></Image> 那不行。有什么好处?我得到一个NullReferenceException。。。但这对我来说没有意义?你可
<Image Name="UL_Team1_Image" Grid.Row="1" Grid.Column="1" Margin="5" Source="Team Logos\ARI.tif"></Image>
那不行。有什么好处?我得到一个NullReferenceException。。。但这对我来说没有意义?你可以在你的代码中使用它,我认为,它比使用
ImageSourceConverter
更快
BitmapImage bimage = new BitmapImage();
bimage.BeginInit();
bimage.UriSource = new Uri("Team Logos\\ARI.tif", UriKind.Relative);
bimage.EndInit();
UL_ImageArr[a].Source = bimage;
如果要使用ImageSourceConverter
,必须按包uri引用图像文件:
var converter = new ImageSourceConverter();
UL_ImageArr[a].Source =
(ImageSource)converter.ConvertFromString("pack://application:,,,/Team Logos/ARI.tif");
在代码隐藏中,您通常会编写完整的参考图像资源 所以你要么写
UL_ImageArr[a].Source = (ImageSource)new ImageSourceConverter().ConvertFromString(
"pack://application:,,,/Team Logos/ARI.tif");
或
或
如果您在WinRt上,请使用此选项
string url = "ms-appx:///Assets/placeHolder.png";
return new BitmapImage(new Uri(url));
谢谢,成功了!奇怪的是,我在另一个项目中使用了convertfromstring功能,效果很好。。不知道为什么这个项目不起作用。无论如何,tyvm!!为什么这么复杂?BitmapImage有一个接受Uri参数的构造函数。这样就节省了BeginInit和EndInit调用。只需编写
UL_ImageArr[a].Source=新的位图图像(新的Uri(…)
@Clemens,这是一种通用的初始化类型,您可以在BeginInit
anfEndInit
之间调整BitmpSource
,这在位图构造函数初始化中是不可能的。@HamletHakobyan是的,但这里不需要这样做。保持简单。
UL_ImageArr[a].Source = new BitmapImage(new Uri(
"pack://application:,,,/Team Logos/ARI.tif"));
UL_ImageArr[a].Source = BitmapFrame.Create(new Uri(
"pack://application:,,,/Team Logos/ARI.tif"));
string url = "ms-appx:///Assets/placeHolder.png";
return new BitmapImage(new Uri(url));