KJSR
KJSR

Reputation: 1757

Update an object Property based on other properties

I am trying to update a property based on value from 2 other properties.

I am using INotifyPropertyChanged here.

So basically I have 3 properties A, B and C. The property I am updating is C here based on A and B. I am able to update property value of C from A and B. So property C will be an addition of property A and B (C = A + B). It works fine when one value is passed from either A or B but when values from both properties are passed it only takes in value from the last property value passed. I know I need to increment the value of C when value from each property is passed. But what is the best way to achieve this?

Here is my code:

private int? _a;
public int? A
{
   get => _a;
   set
   {
       _a = value;
       OnPropertyChanged($"A");
       C = _a;
   }
 }

private int? _b;
public int? B
{
    get => _b;
    set
    {
       _b = value;
       OnPropertyChanged($"B");
       C = _b;
    }
 }

 private int? _c;
 public int? C
 {
    get => _c;
    set
    {
       _c = value;
    }
 }

 public event PropertyChangedEventHandler PropertyChanged;

 [NotifyPropertyChangedInvocator]
 protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
 {
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
 }

Update

Sorry for the confusion above, basically I am trying to update the value of property C when property A and B are passed through. So property C will be an addition of property A and B (C = A + B). Hope this clears the confusion?

Upvotes: 0

Views: 1942

Answers (1)

Steve Todd
Steve Todd

Reputation: 1270

Given the above clarification, what you'd do is something like:

private int? _a;
public int? A
{
   get => _a;
   set
   {
       if (value.HasValue != _a.HasValue || value.GetValueOrDefault(0) != _a.GetValueOrDefault(0))
       {
          _a = value;
          OnPropertyChanged();
          OnPropertyChanged(nameof(C));
       }
   }
 }

private int? _b;
public int? B
{
    get => _b;
    set
    {
       if (value.HasValue != _b.HasValue || value.GetValueOrDefault(0) != _b.GetValueOrDefault(0))
       {
          _a = value;
          OnPropertyChanged();
          OnPropertyChanged(nameof(C));
       }
    }
 }

 public int? C
 {
    get => A + B;
 }

 public event PropertyChangedEventHandler PropertyChanged;

 [NotifyPropertyChangedInvocator]
 protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
 {
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
 }

Upvotes: 2

Related Questions