RX:如何将IObservable <object>绑定到属性(ReactiveUI)

时间:2019-04-23 08:52:04

标签: c# wpf observable system.reactive reactiveui

我有一个MyClientIObservable<IStatus>)类Client.StatusStream()。现在,我想结合使用ReactiveXReactiveUI。但是文档没有提供如何一起使用它们的任何示例。

到目前为止,我已经尝试了一些扩展方法(例如.ToProperty),但是它们不起作用。

public partial class MainWindow : ReactiveWindow<AppViewModel>
{
    public MainWindow()
    {
        InitializeComponent();
        ViewModel = App.Container.GetInstance<AppViewModel>();
        this.WhenActivated(r =>
            {
                this.OneWayBind(ViewModel, viewModel => viewModel.Status.AoiStatus, view => view.StatusTxtbl.Text).DisposeWith(r);
                this.OneWayBind(ViewModel, viewModel => viewModel.Status.OperationMode, view => view.OpModeTxtbl.Text).DisposeWith(r);
                this.OneWayBind(ViewModel, viewModel => viewModel.Status.TestPlan, view => view.TestplanTxtbl.Text).DisposeWith(r);
            });
    }

    private async void ButtonGetStatus_OnClick(object sender, RoutedEventArgs e)
    {
        // the manual mode to get the actual status information
        var status = await ViewModel.Client.GetStatusAsync();
        ViewModel.Status = status;
    }
}

public class AppViewModel : ReactiveObject
{
    private IStatus _Status;
    public IStatus Status
    {
        get => _Status;
        set => this.RaiseAndSetIfChanged(ref _Status, value);
    }

    public MyClient Client { get; }

    public AppViewModel(MyClient client)
    {
        Client = client;
        // automatically pushes every new status information
        Client.StatusStream(); // <- How to get the data out there?
    }
}

信息

要通知gui有关新更新,必须使用ObserveOnDispatcher,请参阅https://stackoverflow.com/a/55811495/6229375

1 个答案:

答案 0 :(得分:4)

Status定义为output property

public class AppViewModel : ReactiveObject
{
    private readonly ObservableAsPropertyHelper<IStatus> _status;
    public string Status => _status.Value;

    public MyClient Client { get; }

    public AppViewModel(MyClient client)
    {
        Client = client;
        Client.StatusStream().ToProperty(this, x => x.Status, out _status);
    }
}