从可移植类库更新UI线程 [英] Update UI thread from portable class library
问题描述
我有一个运行在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);
}
然后,在有权访问调度程序的项目中,实现接口:
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屋!