异步填充Image控件数组报错:需设置UriSource或StreamSource属性
问题:WPF中BitmapImage加载图片报错“Property 'UriSource' or property 'StreamSource' must be set.”
我尝试通过以下代码用Image控件填充StackPanel:遍历存储图片路径的List<String> files集合,调用fillPreviewBottom方法返回Image对象,再把PreviewImages数组里的控件添加为子元素。代码如下:
private async void btnOpenFilesClick(object sender, RoutedEventArgs e) { for (int i = 0; i < files.Count; i++) { PreviewImages[i] = await fillPreviewBottom(files[i]); } } private async Task<Image> fillPreviewBottom(string file) { Image img = new(); BitmapImage bmImg = new(); bmImg.BeginInit(); bmImg.CacheOption = BitmapCacheOption.OnDemand; bmImg.DecodePixelWidth = 200; bmImg.EndInit(); bmImg.UriSource = new Uri(file); img.Source = bmImg; img.Margin = new Thickness(5); return img; }
运行上述代码时出现错误:"Property 'UriSource' or property 'StreamSource' must be set."
我曾尝试在加载实际图片的for循环前,用示例图片初始化所有Image控件,但问题依旧:
for (int i = 0; i < files.Count; i++) { var s = new BitmapImage(); s.BeginInit(); s.UriSource = new Uri("sample.jpg"); s.DecodePixelHeight = 10; s.EndInit(); var im = new Image(); im.Source = s; PreviewImages[i] = im; }
解决方法
问题出在fillPreviewBottom方法里,你在调用bmImg.EndInit()之后才设置UriSource。BitmapImage的初始化规则是:必须在BeginInit()和EndInit()之间设置UriSource(或者StreamSource),否则就会触发这个错误。
修正后的代码如下:
private async void btnOpenFilesClick(object sender, RoutedEventArgs e) { for (int i = 0; i < files.Count; i++) { PreviewImages[i] = await fillPreviewBottom(files[i]); } } private async Task<Image> fillPreviewBottom(string file) { Image img = new(); BitmapImage bmImg = new(); bmImg.BeginInit(); // 将UriSource移到BeginInit和EndInit区间内 bmImg.UriSource = new Uri(file); bmImg.CacheOption = BitmapCacheOption.OnDemand; bmImg.DecodePixelWidth = 200; bmImg.EndInit(); img.Source = bmImg; img.Margin = new Thickness(5); return img; }
额外提示:如果加载的是本地文件路径,建议指定UriKind.Absolute避免路径解析出错,写法如下:bmImg.UriSource = new Uri(file, UriKind.Absolute);
内容的提问来源于stack exchange,提问作者Max
相关产品推荐
相关产品推荐

