0

Not sure what I'm doing wrong:

       private at = "0";
       public string AT
        {
            get
            {
                return aT;
            }
            set
            {
                aT = value;
                this.RaiseAndSetIfChanged(ref aT, value);
            }
        }

Setting this on the ViewModel using AT = "Something", the Raise is called and the View is set initially. However, as the AT gets called continuously (at least one update per second), this does not update after the initial set (the original value of aT)

this.WhenAnyValue(x => x.ViewModel.AT).Subscribe(x => Debug.WriteLine("Change in AT:" + x)); // using this to debug

What seems to work for a while is this:

        set
        {
            aT = value;
            this.RaisePropertyChanged();
        }

However, after successfully getting one value (aside from the initial set), it crashes! What am I doing wrong?

Edit:

This property is changed in an async event handler. The property is changed on every occasion when I breakpoint. This occurs around 1 per second:

private async void ValueChanged(Something sender, SomeArgs args)
        {
            //Computation code here
            AT= string.Format("{0:0.0####}", ATOrigin);
            // Property is set - I checked
           // More code here
        }
Tyress
  • 3,573
  • 2
  • 22
  • 45

1 Answers1

5

Per the name, RaiseAndSetIfChanged will set the field passed by reference if the new value is different.

You're setting the field value before you call this, so there is never any change. Remove this, and it will work:

private string at;

public string AT 
{
    get { return at; }
    set { this.RaiseAndSetIfChanged(ref at, value); }
}

The documentation has some examples.

Charles Mager
  • 25,735
  • 2
  • 35
  • 45
  • Thanks for your answer, but unfortunately this still is not working for me. Breakpointing shows that the field has changed, initially set or not. The View does not see the change, and neither does the ViewModel when I do `this.WhenAnyValue(x => x.AT).Subscribe(x => Debug.WriteLine("Change in AT (VM): " + x));` . I even threw in a ObserveOn(RxApp.MainThreadScheduler) but no change – Tyress Apr 12 '16 at 06:55
  • You need to provide a [mcve] that demonstrates your issue. Taking your code with my change in a basic WPF app with a timer that sets the property every second, I get a line written to the console every second. – Charles Mager Apr 12 '16 at 07:29
  • Some years later I encounter the same problem, it is hard to make a reproductible example because it seems to happen not all the time. I subscribe to the PropertyChanged event normally (PropertyChanged += ...) and it is well notified but `this.WhenAnyValue` does not fire all the time – polkduran Dec 04 '20 at 12:08