我应该能够访问属于View的Dispatcher,我需要将它传递给ViewModel.但是视图应该不知道关于ViewModel的任何信息,那么如何传递它呢?是引入一个接口,还是不将其传递给实例,而是创建一个将由视图编写的全局分派器单例?您如何在MVVM应用程序和框架中解决此问题?
编辑:请注意,因为我的ViewModel可能是在后台线程中创建的,所以我不能只在ViewModel的构造函数中执行Dispatcher.Current
.
我应该能够访问属于View的Dispatcher,我需要将它传递给ViewModel.但是视图应该不知道关于ViewModel的任何信息,那么如何传递它呢?是引入一个接口,还是不将其传递给实例,而是创建一个将由视图编写的全局分派器单例?您如何在MVVM应用程序和框架中解决此问题?
编辑:请注意,因为我的ViewModel可能是在后台线程中创建的,所以我不能只在ViewModel的构造函数中执行Dispatcher.Current
.
我使用接口IContext抽象了调度器:
public interface IContext
{
bool IsSynchronized { get; }
void Invoke(Action action);
void BeginInvoke(Action action);
}
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.
Update (example from pastebin link in comments):个
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);
}
}