Dot-Net

如何將 UI Dispatcher 傳遞給 ViewModel

  • March 1, 2010

我應該能夠訪問屬於我需要將其傳遞給 ViewModel 的視圖的調度程序。但是View應該對ViewModel一無所知,那怎麼傳呢?引入一個介面還是不將其傳遞給實例,而是創建一個將由視圖編寫的全域調度程序單例?您如何在 MVVM 應用程序和框架中解決這個問題?

編輯:請注意,由於我的 ViewModels 可能是在後台執行緒中創建的,因此我不能只Dispatcher.Current在 ViewModel 的建構子中執行此操作。

我已經使用介面IContext抽象了 Dispatcher :

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);
   }
}

引用自:https://stackoverflow.com/questions/2354438