如何将 UI Dispatcher 传递给 ViewModel [英] How to pass the UI Dispatcher to the ViewModel

查看:25
本文介绍了如何将 UI Dispatcher 传递给 ViewModel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该能够访问 Dispatcher属于我需要将它传递给 ViewModel 的视图.但是View应该对ViewModel一无所知,那怎么传递呢?引入一个接口,或者不是将它传递给实例,而是创建一个将由 View 编写的全局调度程序单例?您如何在 MVVM 应用程序和框架中解决这个问题?

I'm supposed to be able to access the Dispatcher that belongs to the View I need to pass it to the ViewModel. But the View should not know anything about the ViewModel, so how do you pass it? Introduce an interface or instead of passing it to the instances create a global dispatcher singleton that will be written by the View? How do you solve this in your MVVM applications and frameworks?

请注意,由于我的 ViewModel 可能是在后台线程中创建的,因此我不能只在 ViewModel 的构造函数中执行 Dispatcher.Current.

Note that since my ViewModels might be created in background threads I can't just do Dispatcher.Current in the constructor of the ViewModel.

推荐答案

我使用接口抽象了 Dispatcher IContext:

I have abstracted the Dispatcher using an interface IContext:

public interface IContext
{
   bool IsSynchronized { get; }
   void Invoke(Action action);
   void BeginInvoke(Action action);
}

这样做的好处是您可以更轻松地对 ViewModel 进行单元测试.
我使用 MEF(托管扩展框架)将接口注入我的 ViewModel.另一种可能性是构造函数参数.不过,我更喜欢使用 MEF 进行注射.

This has the advantage that you can unit-test your ViewModels more easily.
I inject the interface into my ViewModels using the MEF (Managed Extensibility Framework). Another possibility would be a constructor argument. However, I like the injection using MEF more.

更新(来自评论中的 pastebin 链接的示例):

public sealed class WpfContext : IContext
{
    private readonly Dispatcher _dispatcher;

    public bool IsSynchronized
    {
        get
        {
            return this._dispatcher.Thread == Thread.CurrentThread;
        }
    }

    public WpfContext() : this(Dispatcher.CurrentDispatcher)
    {
    }

    public WpfContext(Dispatcher dispatcher)
    {
        Debug.Assert(dispatcher != null);

        this._dispatcher = dispatcher;
    }

    public void Invoke(Action action)
    {
        Debug.Assert(action != null);

        this._dispatcher.Invoke(action);
    }

    public void BeginInvoke(Action action)
    {
        Debug.Assert(action != null);

        this._dispatcher.BeginInvoke(action);
    }
}

这篇关于如何将 UI Dispatcher 传递给 ViewModel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆