关于C# MVVM Toolkit中NotifyPropertyChangedFor的疑问
问题解答:MVVM Toolkit中NotifyPropertyChangedFor的作用差异
先明确两段代码的核心区别,以及[NotifyPropertyChangedFor]的实际作用:
第一段代码生效的原因
第一段里的MyProp是只读计算属性,它的值直接绑定到inputSystemName:
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}"); }
当inputSystemName变化时:
[ObservableProperty]自动为InputSystemName触发PropertyChanged事件[NotifyPropertyChangedFor(nameof(MyProp))]会额外触发一次针对MyProp的PropertyChanged事件- UI收到
MyProp的变更通知后,会重新调用它的getter获取值——而因为MyProp直接返回最新的inputSystemName,所以UI能显示更新后的值
第二段代码无效的原因
第二段里的MyProp是独立的读写属性,有自己的私有字段myProp,和inputSystemName没有任何关联:
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}"); }
当inputSystemName变化时:
[NotifyPropertyChangedFor(nameof(MyProp))]确实会触发MyProp的PropertyChanged事件- 但
myProp的字段值根本没被修改!UI收到通知后去取MyProp的值,得到的还是原来的myProp,所以看起来完全没更新
关键原理
[NotifyPropertyChangedFor]的作用只是告诉UI某个属性可能变了,需要重新读取它的值,而不是自动帮你修改这个属性的字段值。
如果要让第二段代码生效,你得手动在OnInputSystemNameChanged里给myProp赋值,比如:
partial void OnInputSystemNameChanged(string? oldValue, string newValue) { Debug.WriteLine($"InputSystemName changed from {oldValue} to {newValue}"); myProp = newValue; // 手动更新myProp的值 Debug.WriteLine($"MyProp is now {MyProp}"); }
这样UI收到MyProp的变更通知后,读取到的就是新值了。
内容的提问来源于stack exchange,提问作者Ali Jafarbiglookarami
相关产品推荐
相关产品推荐

