首页 > 解决方案 > 将WhenAnyValue 与WhenAnyObservable 一起使用时遇到问题

问题描述

如果另一个属性正在更改,我试图避免更新一个属性。所以我想出了以下(在我的 ViewModel 中):

this.WhenAnyObservable(
    x => x.WhenAnyValue( y => y.Asset.CurrentValuation ),
    x => x.Changing,
    (currentValuation, changing) => changing.PropertyName != "CurrentValuationCalculated"
)

但是,ReactiveUI 在内部抛出以下错误ExpressionRewriter.VisitMethodCall

throw new NotSupportedException("Index expressions are only supported with constants.")

如果我删除该WhenAnyValue行,它会起作用。所以我假设这与里面的表达式有关WhenAnyValue

如果不深入研究ExpressionRewriter代码的实际作用,它在抱怨什么?我犯了某种简单的错误吗?

更新

所以我输入了这个:

this.WhenAnyObservable(
    x => x.Asset.CurrentValuation,
    x => x.Changing,
    ( currentValuation, changing ) => changing.PropertyName != "CurrentValuationCalculated"
)

但是,编译器抱怨x.Asset.CurrentValuation并说:

Cannot implicitly convert type 'decimal?' to 'System.IObservable<ReactiveUI.IReactivePropertyChangedEventArgs<ReactiveUI.IReactiveObject>>'

标签: wpfreactiveui

解决方案


简短的回答是肯定的。

更长的答案是WhenAnyObservable会为您提供更改通知,因此您实际上并不需要WhenAnyValue. 您通常会WhenAnyValue在 ViewModel 属性上使用来强制订阅更改通知。可观察序列本质上是通过OnNext

编辑

请注意,下面我正在观察IObservable中的WhenAnyObservable和 中的视图模型属性WhenAnyValue。您无需解开调用中WhenAnyObservable的值即可获取值。

public class MainViewModel : ReactiveObject
{
    private string _property;

    public IObservable<bool> MyObservabe { get; }

    public string MyProperty { get => _property; set => this.RaiseAndSetIfChanged(ref _property, value); }

    public MainViewModel()
    {
        MyObservabe = Observable.Interval(TimeSpan.FromSeconds(1)).Select(x => x > 5);

        this.WhenAnyObservable(x => x.MyObservabe);

        this.WhenAnyValue(x => x.MyProperty);
    }
}

推荐阅读