MVVM,线程和图像源DataBinidng

Mic*_*ixx 1 wpf multithreading image mvvm

我有一个MVVM实现,其中我有一个WPF ListBox,它将包含一个子WPF图像控件的集合.每个控件的Source可能每秒更改3次.当我的列表中只有一个图像时,生活很美,我的应用程序响应迅速.当我开始有4或5个我的应用程序子图像时,我的应用程序开始研磨,我还应该提到我必须为每个新的和/或更新的图像进行Bitmap到BitmapSource转换.

我应该如何更新我的子控件Source属性,同时尽可能保持我的应用程序响应?

这是我的ViewModel中的当前代码:

public BitmapSource CameraBitmapSource
    {
        get
        {
            Application.Current.Dispatcher.BeginInvoke((Action)delegate
                    {
                        BuildImageSource();
                    }, DispatcherPriority.Background);

            return this.cameraBitmapSource;
         }
    }
Run Code Online (Sandbox Code Playgroud)

BuildImageSource()是我获取新位图并转换为BitmapSource然后分配给我的私有cameraBitmapSource对象的地方.

Tho*_*que 5

因为您使用Dispatcher.BeginInvoke,所以您正在UI线程上完成所有工作,这会使您的应用无响应.您应该在单独的线程上构建映像.最简单的方法是使绑定异步,并BuildImageSource直接调用您的方法.

视图模型

public BitmapSource CameraBitmapSource
{
    get
    {
        BuildImageSource();
        return this.cameraBitmapSource;
    }
}
Run Code Online (Sandbox Code Playgroud)

XAML

<Image Source="{Binding CameraBitmapSource, IsAsync=True}" />
Run Code Online (Sandbox Code Playgroud)

只记得FreezeImageSourceBuildImageSource,以便它可以在UI线程上使用(DependencyObjects只能被创建它们的线程上使用的,除非他们Freezable和冷冻)