首页 > 解决方案 > ReactiveUI WhenAnyValue ToPropertyEx 到一个可为空的小数

问题描述

使用可以为空的小数作为变量,[Reactive] public decimal? CustomPrice { get; set; }我正在尝试使用以下内容对其进行更新:

this.WhenAnyValue(x => x.DiscountPercent, x => x.DiscountFlat, x=>x.UnitPriceOriginal,
   (percent, flat, orig) => ((percent > 0) || (flat > 0)) ? orig * percent - flat : (decimal?)null)
   .ToPropertyEx(this, x => x.CustomPrice);

DiscountPercent DiscountFlat UnitPriceOriginal都是十进制变量。DiscountPercent DiscountFlat从数据库或用户输入字段中设置。CustomPrice也可以从用户输入字段进行编辑,该字段一直在努力更新CustomPrice. CustomPrice然后使用以下方法设置十进制值UnitPrice

this.WhenAnyValue(x => x.CustomPrice, x => x.UnitPriceOriginal,
   (custom, orig) => custom ?? orig)
   .ToPropertyEx(this, x => x.UnitPrice);

我需要在CustomPrice输入值时更新DiscountPercent和/或DiscountFlat需要将null设置UnitPriceUnitPriceOriginal. 使用第一块代码,我得到一个运行时错误:

System.ArgumentException:“ObservableAsPropertyHelper`1[System.Nullable`1[System.Decimal]] 类型的对象”无法转换为“System.Nullable`1[System.Decimal]”类型。

我尝试了许多不同的方法来解决这个问题,但是在更新一个可为空的变量时我遇到了错误。有没有不同的方法可以在运行时将可为空的小数设置为 Observable?有什么我想念的吗?

标签: c#reactiveui

解决方案


确保在您使用ReactiveObservableAsProperty属性的项目中,您可以直接引用ReactiveUI.Fody包;它不能被另一个项目隐式引用。如果没有这种直接引用,FodyWeavers.xml则不会创建文件,并且您将从反应属性中获得奇怪的行为。


推荐阅读