RaisePropertyChanged 的作用可以理解成一句话:

主动告诉 WPF:“HelloCountText 这个属性的值变了,请重新读取它,并刷新绑定了它的界面。”

完整代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _009_入门MVVMLight.ViewModels
{
public class CommandViewModel : ViewModelBase
{
private int _helloCount;
private string _greeting = "你好,MvvmLight";

public RelayCommand SayHelloCommand { get; private set; }

public CommandViewModel()
{
SayHelloCommand = new RelayCommand(ExecuteSayHello);
}

private void ExecuteSayHello()
{
HelloCount++;
RaisePropertyChanged(nameof(HelloCountText));
}

public string HelloCountText
{
get { return "已发送问候:" + HelloCount + " 次"; }
}

public string Greeting
{
get { return _greeting; }
set { Set(ref _greeting, value, nameof(Greeting)); }
}

public int HelloCount
{
get { return _helloCount; }
private set { Set(ref _helloCount, value, nameof(HelloCount)); }
}
}
}

先看这段代码在做什么

1
2
3
4
5
private void ExecuteSayHello()
{
HelloCount++;
RaisePropertyChanged(nameof(HelloCountText));
}

HelloCount++ 会修改计数,但界面上的统计文字绑定的是 HelloCountText:

1
2
3
4
public string HelloCountText
{
get { return "已发送问候:" + HelloCount + " 次"; }
}

HelloCountText 没有自己的字段,也没有 setter。它是每次被读取时,临时用 HelloCount 拼出来的。所以 HelloCount 变了,WPF 并不会自动知道 HelloCountText 也要跟着变。

完整流程

  1. 用户点击按钮。
  2. 命令调用 ExecuteSayHello()。
  3. HelloCount++ 修改计数值。
  4. HelloCount 的 setter 里调用了 Set(...),所以 WPF 会刷新所有绑定 HelloCount 的地方。
  5. 但绑定 HelloCountText 的文字控件没有收到通知,仍然显示旧文字。
  6. 调用 RaisePropertyChanged(nameof(HelloCountText)),WPF 收到通知后重新执行 HelloCountText 的 getter,拿到新字符串,界面才更新。

为什么这里不用 Set

Set 一般用在有字段、有 setter 的属性里,例如:

1
2
3
4
5
public int HelloCount
{
get { return _helloCount; }
private set { Set(ref _helloCount, value, nameof(HelloCount)); }
}

Set 会帮你做三件事:比较新旧值、赋值、发出属性变更通知。

但 HelloCountText 是只读的计算属性,没有 _helloCountText 字段,也没有 setter,所以不能用 Set。这种属性变化时,只能手动调用 RaisePropertyChanged。

nameof(HelloCountText) 是什么

它会在编译时变成字符串 "HelloCountText"。这样写的好处是:

  • 不怕手写字符串拼错。
  • 以后重命名属性时,编译器会一起改。
  • 比直接写 RaisePropertyChanged("HelloCountText") 更安全。

一句话记住

  • Set(...):属性自己有字段和 setter 时,用它自动通知。
  • RaisePropertyChanged(...):属性是计算出来的,或者你想手动通知某个属性时,用它。
  • 通知必须写在值改完之后,否则 WPF 重新读到的还是旧值。

这段代码在笔记的 C:\Users\North\Desktop\WPFStudy\MvvmLight入门学习笔记.md:1477 附近。你可以把它理解成“改完数据后,再补一声广播”,界面才会跟着变。