Using MVVM toolkit for connecting two properties (NotifyPropertyChangedFor)

100 views Asked by At

I have a question about C# new MVVM toolkit.

I wonder why this code works:

string MyProp => inputSystemName;  

[ObservableProperty]
[NotifyPropertyChangedFor(nameof(MyProp))]
private string inputSystemName;
partial void OnInputSystemNameChanged(string? oldValue, string newValue)
{
    Debug.WriteLine($"InputSystemName changed from {oldValue} to {newValue}");
    Debug.WriteLine($"MyProp is now {MyProp}");
}

But this piece of code does not update the value of myProp:

private string myProp = String.Empty;
public string MyProp
{
    get => myProp;
    set => myProp = value;
}  

[ObservableProperty]
[NotifyPropertyChangedFor(nameof(MyProp))]
private string inputSystemName;
partial void OnInputSystemNameChanged(string? oldValue, string newValue)
{
    Debug.WriteLine($"InputSystemName changed from {oldValue} to {newValue}");
    Debug.WriteLine($"MyProp is now {MyProp}");
}

It could potentially be my lack of understanding how the notify property works, but isn't it updating another property?

Thanks!

1

There are 1 answers

0
egeer On BEST ANSWER

That attribute doesn't set the property, it just raises an event to notify that it changed. So you'd need something like this snippet below to actually set the property.

        [ObservableProperty]
        [NotifyPropertyChangedFor(nameof(MyProp))]
        private string inputSystemName;
        partial void OnInputSystemNameChanged(string? oldValue, string newValue)
        {
            Debug.WriteLine($"InputSystemName changed from {oldValue} to {newValue}");
            Debug.WriteLine($"MyProp is now {MyProp}");
            MyProp = newValue; // set the new value to the related property
        }

That attribute will generate the following code

public string? InputSystemName
{
    get => inputSystemName;
    set
    {
        if (SetProperty(ref inputSystemName, value))
        {
            OnPropertyChanged("MyProp");
        }
    }
}

You can see more here https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/generators/observableproperty#notifying-dependent-properties