我应该能够访问调度员属于视图的我需要将其传递给 ViewModel。但是View不应该知道ViewModel的任何信息,那么如何传递它呢?引入一个接口,或者不将其传递给实例,而是创建一个将由视图写入的全局调度程序单例?您如何在 MVVM 应用程序和框架中解决这个问题?
编辑:请注意,由于我的 ViewModel 可能是在后台线程中创建的,所以我不能这样做Dispatcher.Current
在 ViewModel 的构造函数中。
我使用接口抽象了调度程序IContext:
public interface IContext
{
bool IsSynchronized { get; }
void Invoke(Action action);
void BeginInvoke(Action action);
}
这样做的优点是您可以更轻松地对 ViewModel 进行单元测试。
我使用 MEF(托管扩展性框架)将接口注入到我的 ViewModel 中。另一种可能性是构造函数参数。
不过,我更喜欢使用 MEF 进行注射。
更新(来自评论中的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);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)