我正在使用图像控件。我正在为图像控件设置源,如下所示。
但是错误显示无效的URI。
string strUri = String.Format(@"..\..\Assets\Images\Image001.jpeg");
previewImage.Source = BitmapFromUri(new Uri(strUri));
public static ImageSource BitmapFromUri(Uri source)
{
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = source;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.EndInit();
return bitmap;
}
您必须通过设置将其指定为相对URI UriKind.Relative
:
var uri = new Uri(@"..\..\Assets\Images\Image001.jpeg", UriKind.Relative);
也就是说,您的BitmapFromUri
方法可能是多余的(除非您有理由设置BitmapCacheOption.OnLoad
)。您可能还可以使用带有Uri参数的BitmapImage构造函数:
previewImage.Source = new BitmapImage(uri);
另请注意,以上内容假定图像文件实际上已复制到指定的相对路径。如果它是Visual Studio项目的一部分,则最好通过WPF Pack URI将其作为嵌入式资源加载。因此,您必须将其设置Build Action
为Resource
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句