从可移植类库更新 UI 线程 [英] Update UI thread from portable class library

查看:15
本文介绍了从可移植类库更新 UI 线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在 Windows Phone 8 上运行的 MVVM Cross 应用程序,我最近将其移植到使用可移植类库中.

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

视图模型位于可移植类库中,其中一个公开了一个属性,该属性通过数据绑定从 Silverlight for WP 工具包启用和禁用 PerformanceProgressBar.

The view models are within the portable class library and one of them exposes a property which enables and disables a PerformanceProgressBar from the Silverlight for WP toolkit through data binding.

当用户按下按钮时,RelayCommand 会启动一个后台进程,该进程将属性设置为 true,这应该启用进度条并进行后台处理.

When the user presses a button a RelayCommand kicks off a background process which sets the property to true which should enable the progress bar and does the background processing.

在我将它移植到 PCL 之前,我能够从 UI 线程调用更改以确保启用进度条,但是 Dispatcher 对象在 PCL 中不可用.我该如何解决这个问题?

Before I ported it to a PCL I was able to invoke the change from the UI thread to ensure the progress bar got enabled, but the Dispatcher object isn't available in a PCL. How can I work around this?

谢谢

推荐答案

如果您无权访问 Dispatcher,则只需将 BeginInvoke 方法的委托传递给您的类:

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<Action> beginInvoke)
    {
        this.BeginInvoke = beginInvoke;
    }

    protected Action<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.

首先,在你的可移植类库中定义一个 IDispatcher 接口:

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

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

然后,在可以访问dispatcher的项目中,实现接口:

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

然后您可以将此对象作为 IDispatcher 实例传递给您的可移植类库.

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

这篇关于从可移植类库更新 UI 线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆