[WPF] 随笔1:MVVM在ViewModel更新Image控件的BitmapImage值时报:必须在与 DependencyObject 相同的线程上创建 DependencySource

MVVM在ViewModel更新Image控件的BitmapImage值时报:必须在与 DependencyObject 相同的线程上创建 DependencySource
原因:必须在UI线程创建BitmapImage =>链接
解决方案:使用MemoryStream加载图片,并在UI线程转换成BitmapImage =>链接

接下来是我的写法
Tip:我用的是MVVMLight
View Model.cs

  private BitmapImage _PAIPic;
  public BitmapImage PAIPic { get => _PAIPic; set { _PAIPic = value; RaisePropertyChanged(); } }

业务类.cs

  using (var ms = new MemoryStream(new HttpClient().GetByteArrayAsync(item.Url).Result))
  {
    Messenger.Default.Send<MemoryStream>(ms, "SetPAIPic");
  }

Xaml.cs

---------------构造函数-----------------
  //注册Messenger
  Messenger.Default.Register<MemoryStream>(this, "SetPAIPic", (o => SetPAIPic(o)));
---------------方法------------------
        void SetPAIPic(MemoryStream memoryStream)
        {
            Dispatcher.Invoke(() =>
            {
                var bitmap = new BitmapImage();
                bitmap.BeginInit();
                bitmap.CacheOption = BitmapCacheOption.OnLoad;
                bitmap.StreamSource = memoryStream;
                bitmap.EndInit();
                ViewModel.PAIPic = bitmap;
            });
        }

Xaml

  <Image
    Grid.Row="2"
    HorizontalAlignment="Center"
    Source="{Binding ViewModel.PAIPic}"
    Stretch="Fill" />
posted @ 2023-09-25 10:44  牛牛油果  阅读(294)  评论(0编辑  收藏  举报