Search code examples
c#mvvmuwpgetter-setterinotifypropertychanged

UWP C# - Why does NotifyPropertyChanged not fire in this scenario?


In the following scenario, NotifyPropertyChanged does not fire, thus my UI doesn't update (simplified view-model shown):

public class NetworkGraphViewModel : INotifyPropertyChanged
{

     private String byteSentSpeed { get; set; }

     public String ByteSentSpeed { get { return byteSentSpeed; } set { byteSentSpeed = value; NotifyPropertyChanged("ByteSentSpeed"); } }

     private void MyEvent(object sender, object eventArgs)
     {
         byteSentSpeed = byteSentSpeed + 5;
     }

     public void NotifyPropertyChanged(string propertyName)
     {
         if (PropertyChanged != null)
             PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
     }

}

XAML:


<TextBlock Margin="30,5,10,5"  Grid.Column="1" Grid.Row="2" x:Name="bytesSentSpeedBlock" Text="{Binding ByteSentSpeed}"/>

...whereas the following example DOES update the UI:

public class NetworkGraphViewModel : INotifyPropertyChanged
{

     private String byteSentSpeed { get; set; }

     public String ByteSentSpeed { get { return byteSentSpeed; } set { byteSentSpeed = value; NotifyPropertyChanged("ByteSentSpeed"); } }

     private void MyEvent(object sender, object eventArgs)
     {
         byteSentSpeed = byteSentSpeed + 5;
         NotifyPropertyChanged("ByteSentSpeed")
     }

     public void NotifyPropertyChanged(string propertyName)
     {
         if (PropertyChanged != null)
             PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
     }

}

XAML:


<TextBlock Margin="30,5,10,5"  Grid.Column="1" Grid.Row="2" x:Name="bytesSentSpeedBlock" Text="{Binding ByteSentSpeed}"/>

Maybe I'm incorrect in assuming that the change would propagate into the public variable "ByteSentSpeed" through the value assigned to "byteSentSpeed"?

Is this really the most efficient way to do this, or am I doing something stupid?


Solution

  • byteSentSpeed and ByteSentSpeed are two different properties. Setting the former won't invoke the setter of the latter which raises the PropertyChanged event.

    And byteSentSpeed should be a backing field rather than a property:

     private String byteSentSpeed;
     public String ByteSentSpeed { get { return byteSentSpeed; } set { byteSentSpeed = value; NotifyPropertyChanged("ByteSentSpeed"); } }
    

    You should set the property whenever you want to update the UI:

    private void MyEvent(object sender, object eventArgs)
    {
        ByteSentSpeed = ByteSentSpeed + 5;
    }