3

Using a nullable decimal as a variable, [Reactive] public decimal? CustomPrice { get; set; }, I am trying to update it with the following:

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 are all decimal variables. DiscountPercent DiscountFlat are set from the database or from user input fields. CustomPrice is editable from a user input field as well, which has been working to update CustomPrice. CustomPrice is then used to set the decimal value UnitPrice using:

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

I need the CustomPrice to be updated when values are entered into DiscountPercent and/or DiscountFlat otherwise it needs to be null which then sets the UnitPrice to the UnitPriceOriginal. With the first block of code I get a runtime error:

System.ArgumentException: 'Object of type ObservableAsPropertyHelper`1[System.Nullable`1[System.Decimal]]' cannot be converted to type 'System.Nullable`1[System.Decimal]'.'

I have tried many different ways to work around this, but when updating a nullable variable I run into errors. Is there a different way I can set a nullable decimal as an Observable during runtime? Is there something I am missing?

CodyC
  • 33
  • 4
  • Declaring the property without ReactiveUI.Fody attributes should make the code snippet work as expected, so worth trying to remove `[Reactive]` and to declare this particular property as shown here https://www.reactiveui.net/docs/handbook/view-models/#read-write-properties E.g. the `[Reactive]` attribute currently doesn't seem to fully support the new nullability annotations (the work is in progress) – Artyom Oct 29 '20 at 22:21
  • @Artyom I wish it was that simple. Tried that. Different error: >System.Exception: 'Backing field not found for System.Nullable`1[System.Decimal] CustomPrice' – CodyC Nov 03 '20 at 16:12
  • According to https://github.com/reactiveui/ReactiveUI/search?q=Backing+field+not+found the exception seems to be coming from ReactiveUI.Fody so looks like it attempts to generate some stuff anyway. Make sure you remove that `[Reactive]` attribute to prevent that... If you implement a property with `RaiseAndSetIfChanged` then you don't need Fody as you are doing manually what Fody *should* do. – Artyom Nov 04 '20 at 20:44

1 Answers1

4

Make sure that in the project in which you are using the Reactive and ObservableAsProperty attributes you have a direct reference to the ReactiveUI.Fody package; it cannot be implicitly referenced through another project. Without this direct reference, the FodyWeavers.xml file is not created and you will get strange behaviors from your reactive properties.

somethingRandom
  • 811
  • 11
  • 16