在我的ViewModel代码中,我经常会有如下代码:
public bool IsDownloading { get { return _isDownloading.Value; } }
private ObservableAsPropertyHelper<bool> _isDownloading;
...
FileDownloader.WhenAny(x => x.IsDownloading, x => x.Value)
.ToProperty(this, x => x.IsDownloading, out _isDownloading, false, RxApp.MainThreadScheduler);
Run Code Online (Sandbox Code Playgroud)
请注意最后一个RxApp.MainThreadScheduler参数 - 确保对IsDownloading属性的所有更新都发生在主 UI 线程上。
原因是因为可能订阅它。例如,在我的 xaml 视图中,我可能有以下代码:
this.OneWayBind(ViewModel, x => x.IsDownloading, y => y.DownloadProgress.IsActive);
Run Code Online (Sandbox Code Playgroud)
在这里您会看到,IsDownloading它将被路由到IsActive控件上的项目 - 因此任何更新都必须在 UI 线程上进行。所以所有这些都有效。
但我不明白为什么这样ReactiveUI设计。更新发生在 UI 线程上似乎对视图而不是 VM 很重要,所以不应该绑定或OneWayBind确保它在正确的线程上?事实上,如果您查看这些例程的 XML 文档,它们会讨论将事物附加到 View 的内容,因此暗示它应该始终在主线程上。
那么:为什么不OneWayBind和 Bind 隐式强制MainThread?我是否错过了ReactiveUI工作方式(或可以使其工作)的某些内容?