How to pass the UI Dispatcher to the ViewModel

前端 未结 16 647
独厮守ぢ
独厮守ぢ 2020-11-28 02:16

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

16条回答
  •  日久生厌
    2020-11-28 02:26

    I have abstracted the Dispatcher using an interface 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);
        }
    }
    

提交回复
热议问题