ReactiveUI TwoWay绑定复选框

时间:2019-04-23 14:59:50

标签: c# mvvm reactiveui

我有一个带有复选框的简单视图和一个带有[Reactive] bool属性的viewModel。

我希望对UI上的复选框进行更改以传播到viewModel属性,但是当外部因素更新viewModel属性时,我也希望UI复选框状态得到更新。

我认为双向绑定可以做到这一点

this.Bind(ViewModel, viewModel => viewModel.DepthLabel, view => view._depthLabel.IsChecked) .DisposeWith(disposable);

...但是当字段属性因外部因素而变化时,UI不会响应。

我该怎么做才能更新UI?如果这不是双向绑定的意思,那么什么时候应该使用它?

1 个答案:

答案 0 :(得分:1)

What can I do to get the UI to update?

Make sure that the DepthLabel source property is set on the dispatcher thread.

For example, in the following sample code, calling ObserveOnDispatcher() is required for the CheckBox in the view to update:

public class ViewModel : ReactiveObject
{
    [Reactive]
    public bool DepthLabel { get; set; }

    public ViewModel()
    {
        Observable.Timer(TimeSpan.FromSeconds(2))
           .ObserveOnDispatcher()
           .Subscribe(_ => DepthLabel = true);
    }
}