如何在UI调度传递到视图模型 [英] How to pass the UI Dispatcher to the ViewModel

查看:238
本文介绍了如何在UI调度传递到视图模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我应该能够访问属于查看我调度需要将它传递给视图模型。但视图不应该知道的视图模型什么,那么你如何传递?中引入一个接口或者相反,它传递给实例创建将被写入由视图一个全球性的调度单身?你如何在你的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?

编辑:请注意,由于我的ViewModels可能会在后台线程创建我不能只是做 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.

推荐答案

我一直使用的接口抽象的调度程序的 IContext 的:

I have abstracted the Dispatcher using an interface IContext:

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

这样做的好处是,你可以更轻松地单元测试你的ViewModels。
我的界面注入到使用MEF(托管扩展框架)我的ViewModels。另一种可能性是一个构造函数的参数。 不过,我喜欢用注射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.

更新(例如从评论引擎收录链接):

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调度传递到视图模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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