【发布时间】: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