Update UI thread from portable class library

后端 未结 3 1617
庸人自扰
庸人自扰 2020-12-15 12:03

I have an MVVM Cross application running on Windows Phone 8 which I recently ported across to using Portable Class Libraries.

The view models are within the portable

3条回答
  •  时光说笑
    2020-12-15 12:54

    If you don't have access to the Dispatcher, you can just pass a delegate of the BeginInvoke method to your class:

    public class YourViewModel
    {
        public YourViewModel(Action beginInvoke)
        {
            this.BeginInvoke = beginInvoke;
        }
    
        protected Action BeginInvoke { get; private set; }
    
        private void SomeMethod()
        {
            this.BeginInvoke(() => DoSomething());
        }
    }
    

    Then to instanciate it (from a class that has access to the dispatcher):

    var dispatcherDelegate = action => Dispatcher.BeginInvoke(action);
    
    var viewModel = new YourViewModel(dispatcherDelegate);
    

    Or you can also create a wrapper around your dispatcher.

    First, define a IDispatcher interface in your portable class library:

    public interface IDispatcher
    {
        void BeginInvoke(Action action);
    }
    

    Then, in the project who has access to the dispatcher, implement the interface:

    public class DispatcherWrapper : IDispatcher
    {
        public DispatcherWrapper(Dispatcher dispatcher)
        {
            this.Dispatcher = dispatcher;
        }
    
        protected Dispatcher Dispatcher { get; private set; }
    
        public void BeginInvoke(Action action)
        {
            this.Dispatcher.BeginInvoke(action);
        }
    }
    

    Then you can just pass this object as a IDispatcher instance to your portable class library.

提交回复
热议问题