【问题标题】:UWP C# - Why does NotifyPropertyChanged not fire in this scenario?UWP C# - 为什么 NotifyPropertyChanged 在这种情况下不触发?
【发布时间】:2019-12-15 14:51:23
【问题描述】:

在以下场景中,NotifyPropertyChanged 不会触发,因此我的 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;
     }

     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}"/>

...而以下示例确实更新了 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}"/>

也许我假设更改会通过分配给“byteSentSpeed”的值传播到公共变量“ByteSentSpeed”是不正确的?

这真的是最有效的方法吗,还是我在做一些愚蠢的事情?

【问题讨论】:

  • “我在做傻事吗?”——你说的是,不是我。 “也许我假设更改会通过分配给“byteSentSpeed”的值传播到公共变量“ByteSentSpeed”是不正确的?” - 是的,这个。为什么 ByteSentSpeed 属性设置器会因为您为支持字段分配了新值而被调用?由于 setter 本身设置了支持字段,如果在设置字段时自动调用 setter,则无法实现属性;你总是会得到一个无限递归。设置属性值而不是字段:ByteSentSpeed += 5;
  • 彼得的回复解决了你的困惑吗? @PeterDuniho您愿意发表评论作为答案吗?
  • 是的。我不知道为什么直到现在我都无法解决这个问题,特别是因为我之前注意到堆栈溢出错误。谢谢你的解释。

标签: c# mvvm uwp getter-setter inotifypropertychanged


【解决方案1】:

byteSentSpeedByteSentSpeed 是两个不同的属性。设置前者不会调用后者的设置器,后者会引发PropertyChanged 事件。

byteSentSpeed 应该是一个支持字段而不是一个属性:

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

您应该在想要更新 UI 时设置 属性

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-17
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    • 1970-01-01
    • 2017-01-07
    • 2020-04-21
    相关资源
    最近更新 更多