这份笔记只做一件事:用最小的例子,把六个概念一个一个跑起来。

每一章都按同样的顺序写:

  1. 先看一句话原理。
  2. 再写一个很小的界面。
  3. 再写几十行代码。
  4. 运行,看到结果。
  5. 最后才解释关键代码。

正文里的例子都很小,目的是先让你看懂。完整示例项目的代码放在最后附录,用来对照,不要一开始就整包复制。

这份笔记怎么用

  • 按第 1 章到第 6 章的顺序做,不要跳。
  • 每章先照抄“最小界面”和“最小代码”,先让程序跑起来。
  • 跑起来以后,再看“关键代码只看三处”。
  • 报错时先看“常见错误”,大部分问题都在那里。
  • 学完一章,再做一两个小练习,不要一次改太多。

学习路线

图 1:六个章节的关系。先能运行,再学属性通知、命令、消息和线程。

准备环境

项目 建议
操作系统 Windows 10 或 Windows 11
IDE Visual Studio 2022
工作负载 .NET 桌面开发
目标框架 .NET Framework 4.8
NuGet 包 MvvmLightLibs 5.4.1.1

创建项目

  1. 打开 Visual Studio 2022。
  2. 新建“WPF 应用(.NET Framework)”项目。
  3. 项目名写 MvvmLightTour。
  4. 目标框架选 .NET Framework 4.8。
  5. 在“解决方案资源管理器”中右键项目,选择“管理 NuGet 程序包”。
  6. 搜索并安装 MvvmLightLibs,版本选 5.4.1.1。

安装完成后,先按 F5。能看到一个空窗口,就说明环境没问题。

最小项目结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
MvvmLightTour
├─ App.xaml
├─ App.xaml.cs
├─ MainWindow.xaml
├─ MainWindow.xaml.cs
├─ Messages/
│ ├─ StatusMessage.cs
│ └─ TwoWayMessages.cs
└─ ViewModels/
├─ MainViewModel.cs
├─ CounterViewModel.cs
├─ CommandViewModel.cs
├─ ListenerViewModel.cs
├─ MessengerPageViewModel.cs
├─ PeerViewModel.cs
├─ TwoWayPageViewModel.cs
└─ DispatcherPageViewModel.cs

Messages 放消息类,ViewModels 放页面逻辑。界面文件仍然是 MainWindow.xaml。

三层结构

图 2:View 是界面,ViewModel 是页面逻辑,Model 或 Messages 是数据。初学时先记住这三个位置就够了。


1. MvvmLight框架准备

1. 本节目标

让一个空窗口正常启动,并确认 App.xaml 会自动创建 MainWindow。

2. 一句话原理

WPF 启动时先看 App.xaml 里的 StartupUri,发现写的是 MainWindow.xaml,就自动创建并显示主窗口。

所以你不需要在 App.xaml.cs 里写 new MainWindow(),也不需要写 window.Show()。

3. 要改哪里

顺序 文件 位置 要做什么
1 App.xaml Application 标签 确认有 StartupUri="MainWindow.xaml"
2 MainWindow.xaml Window 里面的 Grid 放一个 TabControl
3 MainWindow.xaml.cs MainWindow 构造函数 先不动,后面再设置 DataContext

4. 第一步:写最小界面

打开 MainWindow.xaml,把 Window 里的内容改成这样:

1
2
3
4
5
6
7
8
9
10
11
12
<Window x:Class="MvvmLightTour.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MvvmLight 入门"
Height="420"
Width="640">
<Grid>
<TabControl>
<!-- 后面每一章往这里加一个 TabItem -->
</TabControl>
</Grid>
</Window>

先只写一个空的 TabControl。这一章不需要按钮,也不需要 ViewModel。

5. 第二步:确认启动文件

打开 App.xaml,确认 Application 标签里有这一句:

1
StartupUri="MainWindow.xaml"

它的意思就是:程序启动后,自动打开 MainWindow.xaml。

6. 第三步:运行

按 F5。应该看到一个标题为“MvvmLight 入门”的窗口,里面有一个空的页签区域。

如果窗口能出来,第 1 章就完成了。

7. 关键代码只看三处

位置 代码 意思
App.xaml StartupUri="MainWindow.xaml" 启动时自动打开主窗口
MainWindow.xaml x:Class="MvvmLightTour.MainWindow" 这个 XAML 对应哪个代码文件
MainWindow.xaml <TabControl> 后面每章放一个页签

8. 运行后应该看到什么

  • 窗口能正常打开。
  • 窗口标题是“MvvmLight 入门”。
  • 里面有一个空的页签区域。
  • 没有报错,也没有第二个窗口。

9. 对应截图

第 1 章运行截图

图 3:完整示例项目的第 1 个页签。你的最小版现在只有一个空窗口,这是正常的。

10. 跟做检查点

  • 项目目标框架是 .NET Framework 4.8。
  • 已安装 MvvmLightLibs 5.4.1.1。
  • App.xaml 里有 StartupUri="MainWindow.xaml"。
  • 按 F5 能打开窗口。

11. 常见错误

现象 原因 解决
打开两个窗口 App.xaml.cs 里又手写了 new MainWindow() 删掉手写创建窗口的代码,只保留 StartupUri
找不到 MainWindow StartupUri 文件名写错 确认文件名和路径完全一致
找不到 MvvmLight NuGet 包没装好 重新安装 MvvmLightLibs 5.4.1.1

12. 小练习

  1. 把窗口标题改成“我的第一个 WPF 程序”。
  2. 把窗口高度改成 500,宽度改成 800。
  3. 在 TabControl 里加一个 TabItem Header="测试",里面放一个 TextBlock。

13. 小结与迁移

第 1 章只记住一件事:WPF 的窗口可以由 StartupUri 自动创建。以后新建 WPF 项目,先检查 App.xaml,再检查 MainWindow.xaml,就能快速判断窗口从哪里来。


2. MvvmLight中的相关基类

1. 本节目标

让一个数字变化时,界面文字自动跟着变。

2. 一句话原理

界面绑定属性。属性变了以后,要主动通知界面:“我变了,请重新读一次。”

ObservableObject 和 ViewModelBase 已经帮你写好了通知代码。你只要调用 Set(...) 或 RaisePropertyChanged(...)。

基类关系

图 4:INotifyPropertyChanged 是接口,ObservableObject 实现了它,ViewModelBase 又增加了 Cleanup()。

3. 要改哪里

顺序 文件 位置 要做什么
1 ViewModels/CounterViewModel.cs CounterViewModel 类 写 Count 和 CountText
2 ViewModels/MainViewModel.cs MainViewModel 类 增加 Counter 属性
3 MainWindow.xaml 第 2 个 TabItem 放滑块和文字
4 MainWindow.xaml.cs 构造函数 设置 DataContext

4. 第一步:写最小界面

在 MainWindow.xaml 的 TabControl 里加入第 2 个页签:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<TabItem Header="2 属性通知">
<Grid DataContext="{Binding Counter}">
<StackPanel Margin="24">
<Slider Minimum="0"
Maximum="10"
TickFrequency="1"
IsSnapToTickEnabled="True"
Value="{Binding Count, Mode=TwoWay}" />
<TextBlock Text="{Binding CountText}"
FontSize="28"
Margin="0,16,0,0" />
</StackPanel>
</Grid>
</TabItem>

Slider 用来改数字,TextBlock 用来显示文字。

5. 第二步:写最小代码

在 ViewModels 文件夹中新建 CounterViewModel.cs:

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
using GalaSoft.MvvmLight;

namespace MvvmLightTour.ViewModels
{
public class CounterViewModel : ViewModelBase
{
private int _count;

public int Count
{
get { return _count; }
set
{
if (Set(ref _count, value, nameof(Count)))
{
RaisePropertyChanged(nameof(CountText));
}
}
}

public string CountText
{
get { return "当前数字:" + Count; }
}
}
}

然后在 ViewModels 文件夹中新建 MainViewModel.cs:

1
2
3
4
5
6
7
8
9
10
11
12
namespace MvvmLightTour.ViewModels
{
public class MainViewModel
{
public MainViewModel()
{
Counter = new CounterViewModel();
}

public CounterViewModel Counter { get; private set; }
}
}

6. 第三步:连接界面和数据

打开 MainWindow.xaml.cs,把构造函数改成:

1
2
3
4
5
public MainWindow()
{
InitializeComponent();
DataContext = new MainViewModel();
}

DataContext 可以理解成“界面去哪里找属性”。这里把它设成 MainViewModel,界面就会去 MainViewModel 里找 Counter。

6.1 为什么不是直接 new CounterViewModel()

如果窗口只有一个页面,直接写 DataContext = new CounterViewModel(); 也能用。

但我们的窗口有多个页签,每个页签都有自己的 ViewModel。这时更常见的写法是:先建一个“总”的 MainViewModel,让它把各个页面的 ViewModel 都装起来。

1
2
3
4
5
6
7
8
9
10
11
public class MainViewModel
{
public MainViewModel()
{
Counter = new CounterViewModel();
Command = new CommandViewModel();
}

public CounterViewModel Counter { get; private set; }
public CommandViewModel Command { get; private set; }
}

这里用 Command 只是举例,说明一个柜子可以放多个抽屉;CommandViewModel 会在第 3 章创建。现在先理解“总 ViewModel 负责组合页面 ViewModel”就够了。

可以把它想成一个抽屉柜:

  • MainViewModel 是柜子。
  • Counter、Command 是柜子里的两个抽屉。
  • 每个抽屉里放一个页面自己的 ViewModel。

窗口只认柜子,页签再各自去柜子里拿自己的抽屉。

6.2 DataContext 是怎么一层层传下去的

在 MainWindow 的构造函数里:

1
this.DataContext = new MainViewModel();

这句话的意思是:整个窗口的绑定起点是 MainViewModel。this 就是当前这个 MainWindow,写不写都一样。

然后某个页签写:

1
<Grid DataContext="{Binding Counter}">

它的意思是:这个页签的绑定起点,从 MainViewModel 换成了 MainViewModel.Counter。

可以画成这样:

1
2
3
4
MainWindow.DataContext = MainViewModel
│
├─ {Binding Counter} → CounterViewModel
└─ {Binding Command} → CommandViewModel

所以页签里面再写 {Binding CountText},找的就是 CounterViewModel.CountText。

6.3 为什么属性写 { get; private set; }

1
public CounterViewModel Counter { get; private set; }
  • get:XAML 可以读取这个属性。
  • private set:只有 MainViewModel 自己能在构造函数里赋值,外面不能随便换掉它。
  • 这些属性在构造函数里赋值一次,之后不再变化,所以不需要 Set(...) 通知。

如果以后你要在运行过程中替换某个页面 ViewModel,才需要给它加属性通知。

小提醒:你贴的代码里 BaseClassesViewMode 少了一个 l。如果类名是 BaseClassesViewModel,这里要写成一样的名字,否则会报“找不到类型”。

7. 关键代码只看三处

第一处,Set(ref _count, value, nameof(Count)):

1
2
3
4
if (Set(ref _count, value, nameof(Count)))
{
RaisePropertyChanged(nameof(CountText));
}

Set 做两件事:比较新旧值、赋值并通知 Count 变了。它不知道 CountText 也要变,所以下面还要手动通知一次。

第二处,RaisePropertyChanged(nameof(CountText)):

1
RaisePropertyChanged(nameof(CountText));

它的意思就是:“CountText 变了,界面重新读一遍。”

第三处,界面绑定:

1
<TextBlock Text="{Binding CountText}" />

{Binding CountText} 就是让这个文字控件去读 CountText 属性。

8. 运行后应该看到什么

  • 拖动滑块,数字文字会马上变化。
  • 文字显示“当前数字:0”到“当前数字:10”。
  • 不拖动时,界面保持不动。

9. 对应截图

第 2 章运行截图

图 5:完整示例项目的第 2 个页签。你的最小版只有一个滑块和一行文字,先看懂通知就够了。

10. 跟做检查点

  • 拖动滑块时文字会变。
  • CounterViewModel 继承了 ViewModelBase。
  • Count 的 setter 里调用了 Set(...)。
  • CountText 变化后调用了 RaisePropertyChanged(...)。

11. 常见错误

现象 原因 解决
文字一直不变 没调用 RaisePropertyChanged 在 Set 后面补上
界面找不到 CountText 没设置 DataContext 在构造函数里设置 DataContext = new MainViewModel()
拖动滑块报错 绑定路径写错 检查 {Binding Count} 和属性名是否一致

12. 小练习

  1. 把最大值改成 20。
  2. 增加一个 MinText 属性,显示“最小是 0”。
  3. 把 CountText 改成“现在是 X”。

13. 小结与迁移

属性通知的核心只有一句话:数据变了,要告诉界面。 以后只要界面绑定的值是“算出来的”,例如“共 3 条”“已完成 50%”,就要记得在相关属性变化后补一次 RaisePropertyChanged。


3. MvvmLight中的命令对象

1. 本节目标

点击按钮,执行 ViewModel 里的方法,而不是在窗口代码里写 Click。

2. 一句话原理

按钮不直接认识方法。按钮只认识命令。RelayCommand 把“要执行的方法”包装成一个命令,按钮再绑定这个命令。

命令流程

图 6:按钮发出命令,命令调用 ViewModel 里的方法。

3. 要改哪里

顺序 文件 位置 要做什么
1 ViewModels/CommandViewModel.cs CommandViewModel 类 写计数属性和 IncreaseCommand
2 ViewModels/MainViewModel.cs 构造函数和属性区 增加 Command 属性
3 MainWindow.xaml 第 3 个 TabItem 放文字和按钮

4. 第一步:写最小界面

在 TabControl 里加入第 3 个页签:

1
2
3
4
5
6
7
8
9
10
11
<TabItem Header="3 命令">
<Grid DataContext="{Binding Command}">
<StackPanel Margin="24">
<TextBlock Text="{Binding CountText}"
FontSize="28" />
<Button Content="点我 +1"
Command="{Binding IncreaseCommand}"
Margin="0,16,0,0" />
</StackPanel>
</Grid>
</TabItem>

按钮这里没有 Click,只有 Command。

5. 第二步:写最小代码

在 ViewModels 文件夹中新建 CommandViewModel.cs:

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
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;

namespace MvvmLightTour.ViewModels
{
public class CommandViewModel : ViewModelBase
{
private int _count;

public CommandViewModel()
{
IncreaseCommand = new RelayCommand(Increase);
}

public RelayCommand IncreaseCommand { get; private set; }

public int Count
{
get { return _count; }
private set
{
if (Set(ref _count, value, nameof(Count)))
{
RaisePropertyChanged(nameof(CountText));
}
}
}

public string CountText
{
get { return "点击次数:" + Count; }
}

private void Increase()
{
Count++;
}
}
}

然后在 MainViewModel 的构造函数里加一行:

1
Command = new CommandViewModel();

在属性区加一行:

1
public CommandViewModel Command { get; private set; }

6. 第三步:连接界面和数据

第 3 个页签的根 Grid 已经写了:

1
DataContext="{Binding Command}"

所以页签里的 {Binding IncreaseCommand} 会去 CommandViewModel 里找 IncreaseCommand。

7. 关键代码只看三处

第一处,创建命令:

1
IncreaseCommand = new RelayCommand(Increase);

意思是:点击按钮时,调用 Increase()。

第二处,按钮绑定:

1
Command="{Binding IncreaseCommand}"

意思是:按钮去当前 DataContext 里找 IncreaseCommand。

第三处,真正的方法:

1
2
3
4
private void Increase()
{
Count++;
}

命令只是“包装”,真正干活的还是这个方法。

8. 运行后应该看到什么

  • 点击一次按钮,文字从“点击次数:0”变成“点击次数:1”。
  • 再点一次,变成 2。
  • 按钮不需要写 Click 事件。

9. 对应截图

第 3 章运行截图

图 7:完整示例项目的命令页。你的最小版只有一个按钮和一行文字。

10. 跟做检查点

  • 按钮写的是 Command,不是 Click。
  • IncreaseCommand 在构造函数里创建。
  • 点击按钮后数字会增加。
  • Count 变化后文字会刷新。

11. 常见错误

现象 原因 解决
按钮点了没反应 IncreaseCommand 是 null 检查构造函数有没有创建命令
找不到 RelayCommand 命名空间没引用 加上 using GalaSoft.MvvmLight.CommandWpf;
文字不刷新 忘了通知 CountText 在 Count 的 setter 里补 RaisePropertyChanged

12. 小练习

  1. 增加一个“重置”按钮,把 Count 设回 0。
  2. 把按钮文字改成“加一”。
  3. 让计数到 5 以后,文字显示“已经点了 5 次”。

13. 小结与迁移

命令的写法很固定:先在构造函数里 new RelayCommand(方法名),再在 XAML 里 Command="{Binding 命令属性}"。以后看到按钮,不要先写 Click,先想“这个动作属于哪个 ViewModel”。


4. Messenger对象基本使用

1. 本节目标

发送一条消息,让两个接收者同时收到。

2. 一句话原理

接收者先注册:“有人发 StatusMessage,就调用我的 Receive 方法。”

发送者只发布一条 StatusMessage,不需要知道谁会收到。

Messenger 流程

图 8:先注册,再发送,最后反注册。

3. 要改哪里

顺序 文件 位置 要做什么
1 Messages/StatusMessage.cs StatusMessage 类 写消息内容
2 ViewModels/ListenerViewModel.cs ListenerViewModel 类 写接收方法
3 ViewModels/MessengerPageViewModel.cs MessengerPageViewModel 类 注册、发送、反注册
4 ViewModels/MainViewModel.cs 构造函数和属性区 增加 Messenger 属性
5 MainWindow.xaml 第 4 个 TabItem 放按钮和两行文字

4. 第一步:写最小界面

在 TabControl 里加入第 4 个页签:

1
2
3
4
5
6
7
8
9
10
11
12
<TabItem Header="4 Messenger">
<Grid DataContext="{Binding Messenger}">
<StackPanel Margin="24">
<Button Content="发一条消息"
Command="{Binding SendCommand}" />
<TextBlock Text="{Binding ListenerA.LastMessage}"
Margin="0,16,0,0" />
<TextBlock Text="{Binding ListenerB.LastMessage}"
Margin="0,8,0,0" />
</StackPanel>
</Grid>
</TabItem>

两个 TextBlock 分别显示 A 和 B 最后收到的内容。

5. 第二步:写最小代码

先新建 Messages/StatusMessage.cs:

1
2
3
4
5
6
7
8
9
10
11
12
namespace MvvmLightTour.Messages
{
public class StatusMessage
{
public StatusMessage(string content)
{
Content = content;
}

public string Content { get; private set; }
}
}

再新建 ViewModels/ListenerViewModel.cs:

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
using GalaSoft.MvvmLight;
using MvvmLightTour.Messages;

namespace MvvmLightTour.ViewModels
{
public class ListenerViewModel : ObservableObject
{
private string _lastMessage = "还没收到消息";

public ListenerViewModel(string name)
{
Name = name;
}

public string Name { get; private set; }

public string LastMessage
{
get { return _lastMessage; }
private set { Set(ref _lastMessage, value, nameof(LastMessage)); }
}

public void Receive(StatusMessage message)
{
LastMessage = Name + " 收到:" + message.Content;
}
}
}

最后新建 ViewModels/MessengerPageViewModel.cs:

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
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Messaging;
using MvvmLightTour.Messages;

namespace MvvmLightTour.ViewModels
{
public class MessengerPageViewModel : ViewModelBase
{
private readonly IMessenger _messenger;

public MessengerPageViewModel()
{
_messenger = Messenger.Default;
ListenerA = new ListenerViewModel("A");
ListenerB = new ListenerViewModel("B");

_messenger.Register<StatusMessage>(ListenerA, ListenerA.Receive);
_messenger.Register<StatusMessage>(ListenerB, ListenerB.Receive);

SendCommand = new RelayCommand(Send);
}

public ListenerViewModel ListenerA { get; private set; }

public ListenerViewModel ListenerB { get; private set; }

public RelayCommand SendCommand { get; private set; }

private void Send()
{
_messenger.Send(new StatusMessage("大家好"));
}

public override void Cleanup()
{
_messenger.Unregister<StatusMessage>(ListenerA);
_messenger.Unregister<StatusMessage>(ListenerB);
base.Cleanup();
}
}
}

6. 第三步:连接界面和数据

在 MainViewModel 的构造函数里加:

1
Messenger = new MessengerPageViewModel();

在属性区加:

1
public MessengerPageViewModel Messenger { get; private set; }

页签根 Grid 的 DataContext="{Binding Messenger}" 会找到这个页面 ViewModel。

7. 关键代码逐段看

7.1 先拆开 private readonly IMessenger _messenger;

1
private readonly IMessenger _messenger;
部分 意思
private 私有字段,只有 MessengerPageViewModel 里面的代码能用
readonly 只能在声明时或构造函数里赋值,之后不能再换成另一个 Messenger
IMessenger 字段类型,表示“一个 Messenger 应该能做什么”
_messenger 字段名,下划线是私有字段的常见命名习惯

为什么要在构造函数里写 _messenger = Messenger.Default;?因为后面很多地方都要用 Messenger。每次都写 Messenger.Default.Register(...)、Messenger.Default.Send(...) 会比较长;先把它存到字段里,后面统一写 _messenger,更短,也更容易替换。

readonly 只表示“这个字段不能再指向别的 Messenger”,不表示“不能调用它的方法”。你仍然可以写 _messenger.Send(...) 和 _messenger.Register(...)。

IMessenger 是一个接口。你可以把它理解成“插头标准”:Messenger.Default 是符合这个标准的默认实现。字段写成 IMessenger,以后想换成测试用的 Messenger 也方便。

7.2 Register 这行代码怎么读

1
_messenger.Register<StatusMessage>(ListenerA, ListenerA.Receive);
部分 意思
_messenger 用哪个 Messenger 来登记
Register<StatusMessage> 登记“StatusMessage 这种消息”
ListenerA 谁要接收,也就是 recipient
ListenerA.Receive 收到消息后调用哪个方法,也就是 action
第三个参数默认 false 不强行把接收者留在内存里

Action<StatusMessage> 可以理解成“一个能接收 StatusMessage 参数、没有返回值的方法”。ListenerA.Receive 正好符合这个形状,所以可以直接传进去。

Visual Studio 提示里的三句话,可以这样翻译:

  1. Registers a recipient for a type of message TMessage.
    意思是:给某一种消息登记一个接收者。
  2. The action parameter will be executed when a corresponding message is sent.
    意思是:有人发送这种消息时,就执行你登记的方法。
  3. Registering a recipient does not create a hard reference to it, so if this recipient is deleted, no memory leak is caused.
    意思是:登记不会强引用接收者;接收者被删除后,Messenger 不会把它一直拽在内存里,所以不会造成内存泄漏。

“强引用”可以理解成:Messenger 手里抓着你的对象,只要它不松手,垃圾回收器就不能回收这个对象。

“弱引用”可以理解成:Messenger 只记了一个联系方式,并不拥有这个对象。对象没有别人使用时,就可以被回收。

keepTargetAlive = false 是默认值,表示使用弱引用。初学阶段保持默认就好。

但要注意:弱引用意味着接收者必须由页面自己保存住。我们的 ListenerA、ListenerB 是 ViewModel 的属性,所以它们一直活着。如果你在方法里临时 new 一个监听器,既不给属性也不保存,它可能被垃圾回收,之后就不再收消息。

如果把 keepTargetAlive 改成 true,Messenger 会强引用接收者,接收者不容易被回收;但如果你忘了 Unregister,反而可能造成内存泄漏。所以初学阶段不要改它,保持默认,并在 Cleanup() 里反注册。

7.3 三处关键代码

第一处,注册:

1
_messenger.Register<StatusMessage>(ListenerA, ListenerA.Receive);

意思是:有人发 StatusMessage 时,调用 ListenerA.Receive。

第二处,发送:

1
_messenger.Send(new StatusMessage("大家好"));

发送者只管发,不关心谁收到。

第三处,反注册:

1
_messenger.Unregister<StatusMessage>(ListenerA);

页面关闭时取消注册,避免旧页面继续收到消息。

8. 运行后应该看到什么

  • 点击“发一条消息”,A 和 B 两行文字都变化。
  • A 显示“A 收到:大家好”。
  • B 显示“B 收到:大家好”。

9. 对应截图

第 4 章运行截图

图 9:完整示例项目用三个卡片显示三个监听器。你的最小版只有 A 和 B 两行文字。

10. 跟做检查点

  • A 和 B 都注册了 StatusMessage。
  • 点击按钮后两个都收到。
  • Cleanup() 里调用了 Unregister。
  • 发送和注册用的是同一个消息类型。

11. 常见错误

现象 原因 解决
点击后没人收到 没注册或消息类型不一致 检查 Register<StatusMessage> 和 Send(new StatusMessage(...))
只有 A 收到 B 忘了注册 给 B 也补一条 Register
关闭页面后还收到 没反注册 在 Cleanup() 里 Unregister

12. 小练习

  1. 增加一个监听器 C。
  2. 把消息内容改成“第 1 条消息”。
  3. 增加一个“只让 A 收到”的按钮,思考怎么做。

13. 小结与迁移

Messenger 的基本用法就是三步:注册、发送、反注册。以后遇到“一个变化要通知多个对象”,先定义消息类型,再让接收者注册,不要让发送者保存一堆对象。

最小版先不处理窗口关闭;完整项目会在窗口关闭时调用页面 ViewModel 的 Cleanup()。你现在只要知道反注册代码应该放在 Cleanup() 里就够了。


5. Messenger双向委托调用

1. 本节目标

A 发消息给 B,B 收到后自动回一条给 A。

2. 一句话原理

用两个消息类型表示两个方向:

  • ToBMessage:A 发给 B。
  • ToAMessage:B 回给 A。

每个对象只注册“自己要收的那种消息”,收到后可以再发另一种消息。

双向消息

图 10:A 发 ToBMessage,B 收到后回 ToAMessage。

3. 要改哪里

顺序 文件 位置 要做什么
1 Messages/TwoWayMessages.cs 两个消息类 写 ToBMessage 和 ToAMessage
2 ViewModels/PeerViewModel.cs PeerViewModel 类 写注册、发送、接收
3 ViewModels/TwoWayPageViewModel.cs TwoWayPageViewModel 类 创建 A、B 并连接
4 ViewModels/MainViewModel.cs 构造函数和属性区 增加 TwoWay 属性
5 MainWindow.xaml 第 5 个 TabItem 放按钮和两行文字

4. 第一步:写最小界面

在 TabControl 里加入第 5 个页签:

1
2
3
4
5
6
7
8
9
10
11
12
<TabItem Header="5 双向">
<Grid DataContext="{Binding TwoWay}">
<StackPanel Margin="24">
<Button Content="A 发给 B"
Command="{Binding SendCommand}" />
<TextBlock Text="{Binding PeerA.LastMessage}"
Margin="0,16,0,0" />
<TextBlock Text="{Binding PeerB.LastMessage}"
Margin="0,8,0,0" />
</StackPanel>
</Grid>
</TabItem>

5. 第二步:写最小代码

先新建 Messages/TwoWayMessages.cs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
namespace MvvmLightTour.Messages
{
public class ToBMessage
{
public ToBMessage(string content)
{
Content = content;
}

public string Content { get; private set; }
}

public class ToAMessage
{
public ToAMessage(string content)
{
Content = content;
}

public string Content { get; private set; }
}
}

再新建 ViewModels/PeerViewModel.cs:

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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Messaging;
using MvvmLightTour.Messages;

namespace MvvmLightTour.ViewModels
{
public class PeerViewModel : ObservableObject
{
private readonly IMessenger _messenger;
private readonly bool _isA;
private string _lastMessage = "还没有消息";

public PeerViewModel(string name, bool isA, IMessenger messenger)
{
Name = name;
_isA = isA;
_messenger = messenger;
}

public string Name { get; private set; }

public string LastMessage
{
get { return _lastMessage; }
private set { Set(ref _lastMessage, value, nameof(LastMessage)); }
}

public void Register()
{
if (_isA)
{
_messenger.Register<ToAMessage>(this, ReceiveToA);
}
else
{
_messenger.Register<ToBMessage>(this, ReceiveToB);
}
}

public void SendToOther()
{
if (_isA)
{
_messenger.Send(new ToBMessage("A 找 B"));
}
else
{
_messenger.Send(new ToAMessage("B 回 A"));
}
}

private void ReceiveToB(ToBMessage message)
{
LastMessage = "B 收到:" + message.Content;
_messenger.Send(new ToAMessage("B 收到后回复"));
}

private void ReceiveToA(ToAMessage message)
{
LastMessage = "A 收到:" + message.Content;
}
}
}

最后新建 ViewModels/TwoWayPageViewModel.cs:

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
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Messaging;
using MvvmLightTour.Messages;

namespace MvvmLightTour.ViewModels
{
public class TwoWayPageViewModel : ViewModelBase
{
private readonly IMessenger _messenger;

public TwoWayPageViewModel()
{
_messenger = Messenger.Default;
PeerA = new PeerViewModel("A", true, _messenger);
PeerB = new PeerViewModel("B", false, _messenger);

PeerA.Register();
PeerB.Register();

SendCommand = new RelayCommand(PeerA.SendToOther);
PeerA.SendToOther();
}

public PeerViewModel PeerA { get; private set; }

public PeerViewModel PeerB { get; private set; }

public RelayCommand SendCommand { get; private set; }

public override void Cleanup()
{
_messenger.Unregister<ToAMessage>(PeerA);
_messenger.Unregister<ToBMessage>(PeerB);
base.Cleanup();
}
}
}

6. 第三步:连接界面和数据

在 MainViewModel 的构造函数里加:

1
TwoWay = new TwoWayPageViewModel();

在属性区加:

1
public TwoWayPageViewModel TwoWay { get; private set; }

7. 关键代码只看三处

这里的 _messenger 和第 4 章一样,是一个 private readonly IMessenger 字段,只是这次保存在 PeerViewModel 里面。

第一处,A 注册 ToAMessage,B 注册 ToBMessage:

1
2
3
4
5
6
7
8
if (_isA)
{
_messenger.Register<ToAMessage>(this, ReceiveToA);
}
else
{
_messenger.Register<ToBMessage>(this, ReceiveToB);
}

第二处,A 发 ToBMessage:

1
_messenger.Send(new ToBMessage("A 找 B"));

第三处,B 收到后回 ToAMessage:

1
2
LastMessage = "B 收到:" + message.Content;
_messenger.Send(new ToAMessage("B 收到后回复"));

8. 运行后应该看到什么

  • 程序启动后,A 和 B 已经完成一次往返。
  • 点击“A 发给 B”,两行文字更新。
  • B 收到后自动回复,A 显示“A 收到:B 收到后回复”。

9. 对应截图

第 5 章运行截图

图 11:完整示例项目的 A、B 卡片。你的最小版只有两行文字。

10. 跟做检查点

  • A 注册的是 ToAMessage。
  • B 注册的是 ToBMessage。
  • B 收到 ToBMessage 后会发 ToAMessage。
  • 页面关闭时两个都反注册。

11. 常见错误

现象 原因 解决
A 收不到回复 A 注册了 ToBMessage A 应该注册 ToAMessage
B 收不到消息 B 注册了 ToAMessage B 应该注册 ToBMessage
一直来回发不停 两边收到都回复 只让 B 回复,A 收到后不要再发

12. 小练习

  1. 增加一个“B 主动发给 A”的按钮。
  2. 把回复内容改成“收到,我是 B”。
  3. 思考:如果 A 收到后也回复,会发生什么?

13. 小结与迁移

双向消息的关键不是“网络”,而是两个方向用两个消息类型。以后做“请求—回复”“下单—通知”“保存—刷新”这类流程,都可以先画出两个方向,再分别定义消息。

和上一章一样,最小版先不处理窗口关闭;完整项目会在关闭时调用 Cleanup(),把 A、B 的注册都取消。


6. DispatcherHelper对象使用

1. 本节目标

后台线程计算进度,界面进度条安全地跟着走。

2. 一句话原理

WPF 控件只能由创建它的 UI 线程修改。后台线程不能直接改控件,要把“更新界面”这个动作交给 UI 线程。

DispatcherHelper.CheckBeginInvokeOnUI(...) 就是用来做这件事的。

线程流程

图 12:后台线程负责计算,UI 线程负责更新控件。

3. 要改哪里

顺序 文件 位置 要做什么
1 App.xaml.cs App.OnStartup 初始化 DispatcherHelper
2 ViewModels/DispatcherPageViewModel.cs DispatcherPageViewModel 类 写进度和开始命令
3 ViewModels/MainViewModel.cs 构造函数和属性区 增加 Dispatcher 属性
4 MainWindow.xaml 第 6 个 TabItem 放进度条、文字和按钮

4. 第一步:写最小界面

在 TabControl 里加入第 6 个页签:

1
2
3
4
5
6
7
8
9
10
11
12
13
<TabItem Header="6 后台线程">
<Grid DataContext="{Binding Dispatcher}">
<StackPanel Margin="24">
<ProgressBar Maximum="100"
Value="{Binding Progress, Mode=OneWay}" />
<TextBlock Text="{Binding ProgressText}"
Margin="0,12,0,0" />
<Button Content="开始"
Command="{Binding StartCommand}"
Margin="0,12,0,0" />
</StackPanel>
</Grid>
</TabItem>

5. 第二步:写最小代码

先打开 App.xaml.cs,把 App 类改成:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System.Windows;
using GalaSoft.MvvmLight.Threading;

namespace MvvmLightTour
{
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
DispatcherHelper.Initialize();
}
}
}

再新建 ViewModels/DispatcherPageViewModel.cs:

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
48
49
50
51
52
53
54
using System.Threading;
using System.Threading.Tasks;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Threading;

namespace MvvmLightTour.ViewModels
{
public class DispatcherPageViewModel : ViewModelBase
{
private int _progress;

public DispatcherPageViewModel()
{
StartCommand = new RelayCommand(Start);
}

public RelayCommand StartCommand { get; private set; }

public int Progress
{
get { return _progress; }
private set
{
if (Set(ref _progress, value, nameof(Progress)))
{
RaisePropertyChanged(nameof(ProgressText));
}
}
}

public string ProgressText
{
get { return "进度:" + Progress + "%"; }
}

private void Start()
{
Task.Run(() =>
{
for (var i = 1; i <= 10; i++)
{
Thread.Sleep(200);
var value = i * 10;

DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
Progress = value;
});
}
});
}
}
}

6. 第三步:连接界面和数据

在 MainViewModel 的构造函数里加:

1
Dispatcher = new DispatcherPageViewModel();

在属性区加:

1
public DispatcherPageViewModel Dispatcher { get; private set; }

到这里,MainViewModel 应该包含五个页面 ViewModel。完整样子如下,可以用来核对:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
namespace MvvmLightTour.ViewModels
{
public class MainViewModel
{
public MainViewModel()
{
Counter = new CounterViewModel();
Command = new CommandViewModel();
Messenger = new MessengerPageViewModel();
TwoWay = new TwoWayPageViewModel();
Dispatcher = new DispatcherPageViewModel();
}

public CounterViewModel Counter { get; private set; }
public CommandViewModel Command { get; private set; }
public MessengerPageViewModel Messenger { get; private set; }
public TwoWayPageViewModel TwoWay { get; private set; }
public DispatcherPageViewModel Dispatcher { get; private set; }
}
}

7. 关键代码只看三处

第一处,初始化:

1
DispatcherHelper.Initialize();

它要在 UI 线程上调用,所以放在 App.OnStartup 里最合适。

第二处,后台任务:

1
2
3
4
Task.Run(() =>
{
// 这里的代码在后台线程
});

第三处,回到 UI 线程:

1
2
3
4
DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
Progress = value;
});

Progress 是界面绑定的属性,所以必须在 UI 线程里改。

8. 运行后应该看到什么

  • 点击“开始”,进度条从 0% 走到 100%。
  • 下面的文字同步显示“进度:10%”到“进度:100%”。
  • 界面不会卡住。

9. 对应截图

第 6 章初始界面

图 13:完整示例项目的第 6 个页签初始状态。

第 6 章运行完成

图 14:后台任务完成后,进度条和文字都更新到 100%。

10. 跟做检查点

  • App.OnStartup 调用了 DispatcherHelper.Initialize()。
  • 后台循环用 Task.Run 启动。
  • 修改 Progress 的代码放在 CheckBeginInvokeOnUI 里。
  • 进度条能走到 100%。

11. 常见错误

现象 原因 解决
后台直接改控件报错 跨线程访问了 UI 对象 用 CheckBeginInvokeOnUI 包住
UIDispatcher 是 null 没初始化 在 App.OnStartup 里调用 Initialize()
进度条不动 Progress 没发通知 用 Set(...) 并通知 ProgressText

12. 小练习

  1. 把循环改成 20 步。
  2. 把每步等待改成 100 毫秒。
  3. 增加一个“重置”按钮,把进度设回 0。

13. 小结与迁移

后台线程可以计算,但不能直接改控件。记住这个固定套路:Task.Run 里做耗时计算,CheckBeginInvokeOnUI 里更新界面。以后做下载、导入、批量处理,都可以套这个结构。


跟做后的自测与验证

完整示例项目带有 --self-test 参数,自测会检查属性通知、命令、Messenger 和 DispatcherHelper。

实际运行结果:

1
2
3
4
MvvmLightTour 自测结果
时间:2026-11-16 10:43:36
结果:全部通过
检查项:9

完整示例项目已通过 Release 构建,0 个错误,0 个警告。

最终检查清单

  • 六个章节标题与目录一致。
  • 每章只有一个最小例子。
  • 每章先写界面,再写代码。
  • 代码块都控制在几十行以内。
  • 14 张本地图片都存在。
  • 没有远程图片。
  • 没有使用 Mermaid 等额外图表语法。
  • 示例项目能够编译。
  • 自测 9 项全部通过。

附录:完整示例项目代码

正文是最小版,附录是完整示例项目。两者的类名和界面不完全一样:

  • 正文用来理解概念,代码更短。
  • 附录用来对照完整实现,功能更多。
  • 建议先按正文写完,再打开附录看完整版。
项目文件:MvvmLightTour.csproj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net48</TargetFramework>
<UseWPF>true</UseWPF>
<LangVersion>7.3</LangVersion>
<RootNamespace>MvvmLightTour</RootNamespace>
<AssemblyName>MvvmLightTour</AssemblyName>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="MvvmLightLibs" Version="5.4.1.1" />
</ItemGroup>
</Project>
应用资源:App.xaml
1
2
3
4
5
6
7
8
9
10
11
12
<Application x:Class="MvvmLightTour.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Styles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
应用启动:App.xaml.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System.Windows;
using GalaSoft.MvvmLight.Threading;

namespace MvvmLightTour
{
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
DispatcherHelper.Initialize();
}
}
}
统一样式:Styles.xaml
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<SolidColorBrush x:Key="PageBackgroundBrush" Color="#F4F7FB" />
<SolidColorBrush x:Key="CardBackgroundBrush" Color="#FFFFFF" />
<SolidColorBrush x:Key="PrimaryBrush" Color="#1F5A94" />
<SolidColorBrush x:Key="PrimaryDarkBrush" Color="#153E68" />
<SolidColorBrush x:Key="AccentBrush" Color="#2B9FD8" />
<SolidColorBrush x:Key="TextBrush" Color="#233348" />
<SolidColorBrush x:Key="MutedTextBrush" Color="#66758A" />
<SolidColorBrush x:Key="BorderBrush" Color="#DCE5EF" />
<SolidColorBrush x:Key="SuccessBrush" Color="#1E7B58" />
<SolidColorBrush x:Key="WarningBrush" Color="#B46A16" />
<SolidColorBrush x:Key="ErrorBrush" Color="#B33A3A" />

<Style TargetType="Window">
<Setter Property="FontFamily" Value="Microsoft YaHei UI" />
<Setter Property="FontSize" Value="14" />
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
<Setter Property="Background" Value="{StaticResource PageBackgroundBrush}" />
</Style>

<Style TargetType="TextBlock">
<Setter Property="TextWrapping" Value="Wrap" />
</Style>

<Style TargetType="Button">
<Setter Property="Padding" Value="14,8" />
<Setter Property="Margin" Value="0,0,8,8" />
<Setter Property="MinHeight" Value="34" />
<Setter Property="Background" Value="{StaticResource PrimaryBrush}" />
<Setter Property="Foreground" Value="White" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border x:Name="ButtonBorder"
Background="{TemplateBinding Background}"
CornerRadius="6"
Padding="{TemplateBinding Padding}">
<ContentPresenter HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="ButtonBorder" Property="Opacity" Value="0.88" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter TargetName="ButtonBorder" Property="Opacity" Value="0.72" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="ButtonBorder" Property="Background" Value="#B7C3D0" />
<Setter Property="Foreground" Value="#F3F6F9" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

<Style x:Key="SecondaryButtonStyle" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Background" Value="#E8F0F8" />
<Setter Property="Foreground" Value="{StaticResource PrimaryDarkBrush}" />
</Style>

<Style x:Key="CardStyle" TargetType="Border">
<Setter Property="Background" Value="{StaticResource CardBackgroundBrush}" />
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="CornerRadius" Value="10" />
<Setter Property="Padding" Value="20" />
<Setter Property="Margin" Value="0,0,0,14" />
</Style>

<Style x:Key="SectionTitleStyle" TargetType="TextBlock">
<Setter Property="FontSize" Value="20" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Foreground" Value="{StaticResource PrimaryDarkBrush}" />
<Setter Property="Margin" Value="0,0,0,8" />
</Style>

<Style x:Key="SubtleTitleStyle" TargetType="TextBlock">
<Setter Property="FontSize" Value="16" />
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Foreground" Value="{StaticResource TextBrush}" />
<Setter Property="Margin" Value="0,0,0,6" />
</Style>

<Style x:Key="HintTextStyle" TargetType="TextBlock">
<Setter Property="Foreground" Value="{StaticResource MutedTextBrush}" />
<Setter Property="FontSize" Value="13" />
<Setter Property="LineHeight" Value="22" />
<Setter Property="TextWrapping" Value="Wrap" />
</Style>

<Style x:Key="ValueBadgeStyle" TargetType="Border">
<Setter Property="Background" Value="#EAF4FC" />
<Setter Property="CornerRadius" Value="5" />
<Setter Property="Padding" Value="9,4" />
<Setter Property="HorizontalAlignment" Value="Left" />
</Style>

<Style TargetType="TextBox">
<Setter Property="Padding" Value="10,8" />
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Background" Value="White" />
<Setter Property="VerticalContentAlignment" Value="Center" />
</Style>

<Style TargetType="ListBox">
<Setter Property="BorderBrush" Value="{StaticResource BorderBrush}" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="Background" Value="#FBFCFE" />
<Setter Property="Padding" Value="6" />
</Style>

<Style TargetType="TabItem">
<Setter Property="FontSize" Value="14" />
<Setter Property="Padding" Value="17,10" />
<Setter Property="Foreground" Value="{StaticResource MutedTextBrush}" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TabItem">
<Border x:Name="TabBorder"
Margin="0,0,4,0"
Padding="{TemplateBinding Padding}"
CornerRadius="7,7,0,0"
Background="Transparent">
<ContentPresenter ContentSource="Header"
HorizontalAlignment="Center"
VerticalAlignment="Center" />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter TargetName="TabBorder" Property="Background" Value="White" />
<Setter Property="Foreground" Value="{StaticResource PrimaryBrush}" />
<Setter Property="FontWeight" Value="SemiBold" />
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Foreground" Value="{StaticResource PrimaryBrush}" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

<Style x:Key="TourTabControlStyle" TargetType="TabControl">
<Setter Property="Background" Value="Transparent" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="TabControl">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TabPanel IsItemsHost="True"
Background="Transparent"
KeyboardNavigation.TabIndex="1" />
<Border Grid.Row="1"
Background="White"
BorderBrush="{StaticResource BorderBrush}"
BorderThickness="1"
CornerRadius="0,10,10,10">
<ContentPresenter ContentSource="SelectedContent" />
</Border>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>

<Style TargetType="ProgressBar">
<Setter Property="Height" Value="16" />
<Setter Property="Background" Value="#E8EEF5" />
<Setter Property="Foreground" Value="{StaticResource AccentBrush}" />
</Style>
</ResourceDictionary>
主窗口界面:MainWindow.xaml
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
<Window x:Class="MvvmLightTour.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MvvmLight 入门之旅"
Width="1360"
Height="860"
MinWidth="1100"
MinHeight="700"
WindowStartupLocation="CenterScreen"
Loaded="Window_Loaded"
Closing="Window_Closing">
<Grid x:Name="RootLayout" Background="{StaticResource PageBackgroundBrush}">
<Grid.RowDefinitions>
<RowDefinition Height="112" />
<RowDefinition Height="*" />
<RowDefinition Height="34" />
</Grid.RowDefinitions>

<Border Grid.Row="0" Background="#102D4F">
<Grid Margin="28,18,28,16">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>

<StackPanel>
<TextBlock Text="MVVM LIGHT · WPF"
Foreground="#7CC7F2"
FontSize="12"
FontWeight="SemiBold" />
<TextBlock Text="MvvmLight 入门之旅"
Foreground="White"
FontSize="28"
FontWeight="SemiBold"
Margin="0,5,0,2" />
<TextBlock Text="一个窗口,六个页签:先看环境,再学基类、命令、Messenger 和跨线程。"
Foreground="#C6D8EA"
FontSize="13" />
</StackPanel>

<StackPanel Grid.Column="1"
VerticalAlignment="Center"
HorizontalAlignment="Right">
<Border Background="#1C446D"
CornerRadius="7"
Padding="13,8"
Margin="0,0,0,7">
<TextBlock Text="net48 · MvvmLightLibs 5.4.1.1"
Foreground="#E3F2FD"
FontSize="12" />
</Border>
<TextBlock Text="跟着页签顺序操作,每一步都能直接观察结果"
Foreground="#9FC0DB"
FontSize="12"
HorizontalAlignment="Right" />
</StackPanel>
</Grid>
</Border>

<Grid Grid.Row="1" Margin="18,14,18,0">
<TabControl x:Name="TourTabs"
Style="{StaticResource TourTabControlStyle}"
SelectedIndex="{Binding SelectedTabIndex, Mode=TwoWay}">

<TabItem Header="1 框架准备">
<ScrollViewer VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Disabled">
<Grid Margin="24,20,24,24" DataContext="{Binding Preparation}">
<StackPanel>
<TextBlock Text="1. MvvmLight框架准备"
Style="{StaticResource SectionTitleStyle}" />
<TextBlock Style="{StaticResource HintTextStyle}"
Text="这一节先把“能运行”这件事做好:项目引用 MvvmLight、启动时初始化 DispatcherHelper,然后确认版本和线程信息。" />

<Grid Margin="0,16,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>

<Border Style="{StaticResource CardStyle}" Margin="0,0,14,14">
<StackPanel>
<TextBlock Text="三步完成准备" Style="{StaticResource SubtleTitleStyle}" />
<TextBlock Style="{StaticResource HintTextStyle}"
Text="1. 创建 WPF 项目,目标框架固定为 .NET Framework 4.8。" />
<TextBlock Style="{StaticResource HintTextStyle}"
Text="2. 在项目文件中加入 MvvmLightLibs 包引用。" />
<TextBlock Style="{StaticResource HintTextStyle}"
Text="3. 在应用启动时调用 DispatcherHelper.Initialize()。" />

<Border Background="#102D4F"
CornerRadius="7"
Padding="13,11"
Margin="0,10,0,12">
<TextBlock Text="&lt;PackageReference Include=&quot;MvvmLightLibs&quot; Version=&quot;5.4.1.1&quot; /&gt;"
Foreground="#DCEBFA"
FontFamily="Consolas"
FontSize="12" />
</Border>

<TextBlock Style="{StaticResource HintTextStyle}"
Text="为什么固定版本:MvvmLight 是一个较早的框架,教程代码和 NuGet 包必须使用同一套 API。本文不声称它是最新版本,只保证这份示例在 5.4.1.1 上可编译运行。" />
</StackPanel>
</Border>

<Border Grid.Column="1" Style="{StaticResource CardStyle}" Margin="0,0,0,14">
<StackPanel>
<TextBlock Text="实时环境检查" Style="{StaticResource SubtleTitleStyle}" />
<Grid Margin="0,8,0,10">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="112" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
</Grid.RowDefinitions>
<TextBlock Text="目标框架" Foreground="{StaticResource MutedTextBrush}" />
<TextBlock Grid.Column="1" Text="{Binding TargetFramework}" FontWeight="SemiBold" />
<TextBlock Grid.Row="1" Text="MvvmLight" Foreground="{StaticResource MutedTextBrush}" />
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding PackageVersion}" FontWeight="SemiBold" />
<TextBlock Grid.Row="2" Text="CLR 版本" Foreground="{StaticResource MutedTextBrush}" />
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding RuntimeVersion}" FontWeight="SemiBold" />
<TextBlock Grid.Row="3" Text="界面线程 ID" Foreground="{StaticResource MutedTextBrush}" />
<TextBlock Grid.Row="3" Grid.Column="1" Text="{Binding UiThreadId}" FontWeight="SemiBold" />
</Grid>

<Border CornerRadius="7" Padding="11,9" Margin="0,0,0,10">
<Border.Style>
<Style TargetType="Border">
<Setter Property="Background" Value="#FFF3E3" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsReady}" Value="True">
<Setter Property="Background" Value="#E8F6EF" />
</DataTrigger>
</Style.Triggers>
</Style>
</Border.Style>
<TextBlock Text="{Binding EnvironmentStatus}" FontSize="12" />
</Border>

<Button Content="重新检查环境"
Command="{Binding CheckEnvironmentCommand}"
HorizontalAlignment="Left" />
<TextBlock Foreground="{StaticResource MutedTextBrush}" FontSize="12">
<Run Text="最近检查:" />
<Run Text="{Binding LastCheckTime, Mode=OneWay}" />
</TextBlock>
</StackPanel>
</Border>
</Grid>

<Border Style="{StaticResource CardStyle}" Margin="0,0,0,0">
<StackPanel>
<TextBlock Text="运行后应该看到什么" Style="{StaticResource SubtleTitleStyle}" />
<TextBlock Style="{StaticResource HintTextStyle}"
Text="点击“重新检查环境”后,绿色提示应显示环境检查通过;右侧能看到程序集版本、目标框架和界面线程 ID。若 DispatcherHelper 未初始化,提示会明确指出来。" />
<TextBlock Style="{StaticResource HintTextStyle}"
Margin="0,7,0,0"
Text="跟做检查点:项目没有红色波浪线;解决方案资源管理器中的依赖包含 MvvmLightLibs;按 F5 后窗口能正常出现。" />
</StackPanel>
</Border>
</StackPanel>
</Grid>
</ScrollViewer>
</TabItem>

<TabItem Header="2 相关基类">
<ScrollViewer VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Disabled">
<Grid x:Name="BaseClassesRoot"
Margin="24,20,24,24"
DataContext="{Binding BaseClasses}">
<StackPanel>
<TextBlock Text="2. MvvmLight中的相关基类"
Style="{StaticResource SectionTitleStyle}" />
<TextBlock Style="{StaticResource HintTextStyle}"
Text="数据绑定的关键不是“把值写进属性”,而是“值变化后通知界面”。下面三种写法做的是同一件事,但代码量不同。" />

<Grid Margin="0,16,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>

<Border Style="{StaticResource CardStyle}" Margin="0,0,12,14">
<StackPanel>
<TextBlock Text="默认:自定义" Style="{StaticResource SubtleTitleStyle}" />
<TextBlock Text="INotifyPropertyChanged"
Foreground="{StaticResource PrimaryBrush}"
FontFamily="Consolas"
FontSize="13"
Margin="0,0,0,8" />
<Border Style="{StaticResource ValueBadgeStyle}" Margin="0,4,0,10">
<TextBlock Text="{Binding ManualCounter.Count}" FontSize="24" FontWeight="SemiBold" />
</Border>
<TextBlock Style="{StaticResource HintTextStyle}"
Text="要自己声明 PropertyChanged 事件,并在 setter 中手动触发通知。" />
<Button Content="+1 手工通知"
Margin="0,12,0,0"
Command="{Binding IncrementManualCommand}" />
</StackPanel>
</Border>

<Border Grid.Column="1" Style="{StaticResource CardStyle}" Margin="0,0,12,14">
<StackPanel>
<TextBlock Text="框架:ObservableObject" Style="{StaticResource SubtleTitleStyle}" />
<TextBlock Text="Set(ref field, value)"
Foreground="{StaticResource PrimaryBrush}"
FontFamily="Consolas"
FontSize="13"
Margin="0,0,0,8" />
<Border Style="{StaticResource ValueBadgeStyle}" Margin="0,4,0,10">
<TextBlock Text="{Binding ObservableCounter.Count}" FontSize="24" FontWeight="SemiBold" />
</Border>
<TextBlock Style="{StaticResource HintTextStyle}"
Text="继承 ObservableObject 后,用 Set 同时完成赋值和通知,省掉重复代码。" />
<Button Content="+1 框架通知"
Margin="0,12,0,0"
Command="{Binding IncrementObservableCommand}" />
</StackPanel>
</Border>

<Border Grid.Column="2" Style="{StaticResource CardStyle}" Margin="0,0,0,14">
<StackPanel>
<TextBlock Text="框架:ViewModelBase" Style="{StaticResource SubtleTitleStyle}" />
<TextBlock Text="ObservableObject + Cleanup()"
Foreground="{StaticResource PrimaryBrush}"
FontFamily="Consolas"
FontSize="13"
Margin="0,0,0,8" />
<Border Style="{StaticResource ValueBadgeStyle}" Margin="0,4,0,10">
<TextBlock Text="{Binding FrameworkCounter.Count}" FontSize="24" FontWeight="SemiBold" />
</Border>
<TextBlock Style="{StaticResource HintTextStyle}"
Text="适合做 ViewModel:除了通知属性,还能在页面关闭时重写 Cleanup() 释放资源。" />
<Button Content="+1 ViewModel"
Margin="0,12,0,0"
Command="{Binding IncrementFrameworkCommand}" />
</StackPanel>
</Border>
</Grid>

<Border Style="{StaticResource CardStyle}" Margin="0,0,0,14">
<StackPanel>
<TextBlock Text="三种写法放在一起看" Style="{StaticResource SubtleTitleStyle}" />
<Grid Margin="0,6,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="150" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="34" />
<RowDefinition Height="38" />
<RowDefinition Height="38" />
<RowDefinition Height="38" />
</Grid.RowDefinitions>
<Border Grid.Row="0" Grid.ColumnSpan="3" Background="#EAF2F9" Padding="10,7">
<TextBlock Text="对比项" FontWeight="SemiBold" />
</Border>
<Border Grid.Row="1" BorderBrush="{StaticResource BorderBrush}" BorderThickness="0,0,0,1" Padding="10,8">
<TextBlock Text="需要写什么" />
</Border>
<Border Grid.Row="1" Grid.Column="1" BorderBrush="{StaticResource BorderBrush}" BorderThickness="0,0,0,1" Padding="10,8">
<TextBlock Text="事件、setter、通知方法" />
</Border>
<Border Grid.Row="1" Grid.Column="2" BorderBrush="{StaticResource BorderBrush}" BorderThickness="0,0,0,1" Padding="10,8">
<TextBlock Text="一个 Set 调用" />
</Border>
<Border Grid.Row="2" BorderBrush="{StaticResource BorderBrush}" BorderThickness="0,0,0,1" Padding="10,8">
<TextBlock Text="适合场景" />
</Border>
<Border Grid.Row="2" Grid.Column="1" BorderBrush="{StaticResource BorderBrush}" BorderThickness="0,0,0,1" Padding="10,8">
<TextBlock Text="理解原理、练习基础" />
</Border>
<Border Grid.Row="2" Grid.Column="2" BorderBrush="{StaticResource BorderBrush}" BorderThickness="0,0,0,1" Padding="10,8">
<TextBlock Text="日常 ViewModel、页面清理" />
</Border>
<Border Grid.Row="3" Grid.Column="0" Padding="10,8">
<TextBlock Text="资源释放" />
</Border>
<Border Grid.Row="3" Grid.Column="1" Padding="10,8">
<TextBlock Text="需要自己另写" />
</Border>
<Border Grid.Row="3" Grid.Column="2" Padding="10,8">
<TextBlock Text="重写 Cleanup()" />
</Border>
</Grid>
</StackPanel>
</Border>

<Border Style="{StaticResource CardStyle}" Margin="0,0,0,0">
<StackPanel>
<TextBlock Text="ViewModelBase 的资源释放演示" Style="{StaticResource SubtleTitleStyle}" />
<TextBlock Text="{Binding FrameworkCounter.CleanupLog}"
Style="{StaticResource HintTextStyle}"
Margin="0,0,0,10" />
<StackPanel Orientation="Horizontal">
<Button Content="模拟页面关闭:调用 Cleanup()"
Command="{Binding CleanupCommand}" />
<Button Content="重置本页演示"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding ResetCommand}" />
</StackPanel>
<TextBlock Text="{Binding CleanupMessage}"
Foreground="{StaticResource SuccessBrush}"
FontSize="12" />
</StackPanel>
</Border>
</StackPanel>
</Grid>
</ScrollViewer>
</TabItem>

<TabItem Header="3 命令对象">
<ScrollViewer VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Disabled">
<Grid x:Name="CommandRoot"
Margin="24,20,24,24"
DataContext="{Binding CommandDemo}">
<StackPanel>
<TextBlock Text="3. MvvmLight中的命令对象"
Style="{StaticResource SectionTitleStyle}" />
<TextBlock Style="{StaticResource HintTextStyle}"
Text="命令把“按钮被点击”这件事从代码隐藏文件搬到 ViewModel 中。界面只负责绑定命令,ViewModel 负责决定命令能不能执行、执行后做什么。" />

<Grid Margin="0,16,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="43*" />
<ColumnDefinition Width="57*" />
</Grid.ColumnDefinitions>

<Border Style="{StaticResource CardStyle}" Margin="0,0,14,14">
<StackPanel>
<TextBlock Text="RelayCommand:无参数命令" Style="{StaticResource SubtleTitleStyle}" />
<TextBlock Text="输入问候语,按钮会执行 SayHelloCommand。"
Style="{StaticResource HintTextStyle}"
Margin="0,0,0,7" />
<TextBox Text="{Binding Greeting, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Text="{Binding CanExecuteText}"
Foreground="{StaticResource PrimaryBrush}"
FontSize="12"
Margin="0,8,0,4" />
<Button Content="执行无参数命令"
Command="{Binding SayHelloCommand}" />
<StackPanel Orientation="Horizontal">
<Button Content="锁定发送"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding LockSendCommand}" />
<Button Content="解锁发送"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding UnlockSendCommand}" />
</StackPanel>
<TextBlock Text="{Binding AllowSendText}"
Foreground="{StaticResource MutedTextBrush}"
FontSize="12" />
</StackPanel>
</Border>

<Border Grid.Column="1" Style="{StaticResource CardStyle}" Margin="0,0,0,14">
<StackPanel>
<TextBlock Text="RelayCommand&lt;T&gt;:带参数命令" Style="{StaticResource SubtleTitleStyle}" />
<TextBlock Style="{StaticResource HintTextStyle}"
Text="按钮通过 CommandParameter 把参数交给命令。这里演示把字符串参数转换成整数,再累加到结果中。" />
<StackPanel Orientation="Horizontal" Margin="0,8,0,0">
<Button Content="+1"
Command="{Binding AddNumberCommand}"
CommandParameter="1" />
<Button Content="+5"
Command="{Binding AddNumberCommand}"
CommandParameter="5" />
<Button Content="+10"
Command="{Binding AddNumberCommand}"
CommandParameter="10" />
<Button Content="重置"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding ResetCommand}" />
</StackPanel>
<TextBlock Text="{Binding AddNumberStateText}"
Foreground="{StaticResource MutedTextBrush}"
FontSize="12" />
<Grid Margin="0,12,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Border Background="#EAF4FC" CornerRadius="7" Padding="12,10" Margin="0,0,7,0">
<StackPanel>
<TextBlock Text="{Binding HelloCountText}" FontWeight="SemiBold" />
<TextBlock Text="由无参数命令维护" Foreground="{StaticResource MutedTextBrush}" FontSize="12" />
</StackPanel>
</Border>
<Border Grid.Column="1" Background="#EAF4FC" CornerRadius="7" Padding="12,10" Margin="7,0,0,0">
<StackPanel>
<TextBlock Text="{Binding NumberTotalText}" FontWeight="SemiBold" />
<TextBlock Text="由泛型命令维护" Foreground="{StaticResource MutedTextBrush}" FontSize="12" />
</StackPanel>
</Border>
</Grid>
<TextBlock Text="执行日志" Style="{StaticResource SubtleTitleStyle}" Margin="0,14,0,7" />
<ListBox ItemsSource="{Binding Logs}" Height="150" />
</StackPanel>
</Border>
</Grid>

<Border Style="{StaticResource CardStyle}" Margin="0,0,0,0">
<StackPanel>
<TextBlock Text="CanExecute 的关键点" Style="{StaticResource SubtleTitleStyle}" />
<TextBlock Style="{StaticResource HintTextStyle}"
Text="CanExecute 返回 false 时,按钮会自动变灰。输入框为空或发送开关被锁定时,RelayCommand 会阻止执行;改变状态后要调用 RaiseCanExecuteChanged(),界面才会重新询问一次。" />
</StackPanel>
</Border>
</StackPanel>
</Grid>
</ScrollViewer>
</TabItem>

<TabItem Header="4 Messenger 基础">
<ScrollViewer VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Disabled">
<Grid x:Name="MessengerBasicRoot"
Margin="24,20,24,24"
DataContext="{Binding MessengerBasic}">
<StackPanel>
<TextBlock Text="4. Messenger对象基本使用"
Style="{StaticResource SectionTitleStyle}" />
<TextBlock Style="{StaticResource HintTextStyle}"
Text="Messenger 像一个小型广播站:接收方先登记一个委托方法,发送方发布消息,Messenger 再把消息交给所有已登记的委托。反注册后,委托就不会再被调用。" />

<Border Style="{StaticResource CardStyle}" Margin="0,16,0,14">
<StackPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel>
<TextBlock Text="一条消息,三个监听器" Style="{StaticResource SubtleTitleStyle}" />
<TextBlock Text="{Binding BStatusText}"
Foreground="{StaticResource MutedTextBrush}"
FontSize="12" />
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center">
<Button Content="发送新消息"
Command="{Binding SendMessageCommand}" />
<Button Content="全部注册"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding RegisterAllCommand}" />
<Button Content="让 B 反注册"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding UnregisterBCommand}" />
<Button Content="重新注册 B"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding RegisterBCommand}" />
</StackPanel>
</Grid>
<Grid Margin="0,12,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="150" />
</Grid.ColumnDefinitions>
<TextBox Text="{Binding Draft, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Grid.Column="1"
Text="输入内容会作为广播正文"
Foreground="{StaticResource MutedTextBrush}"
FontSize="12"
VerticalAlignment="Center"
Margin="12,0,0,0" />
</Grid>
</StackPanel>
</Border>

<ItemsControl ItemsSource="{Binding Listeners}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="3" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Border Style="{StaticResource CardStyle}" Margin="0,0,12,14">
<StackPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" Style="{StaticResource SubtleTitleStyle}" />
<Border Grid.Column="1"
Background="#E8F6EF"
CornerRadius="10"
Padding="8,3"
VerticalAlignment="Top">
<TextBlock Text="{Binding RegisteredText}"
Foreground="{StaticResource SuccessBrush}"
FontSize="11" />
</Border>
</Grid>
<TextBlock Text="{Binding ReceivedCountText}"
Foreground="{StaticResource PrimaryBrush}"
FontWeight="SemiBold"
Margin="0,7,0,4" />
<TextBlock Text="{Binding LastMessage}"
Style="{StaticResource HintTextStyle}"
MinHeight="42" />
<TextBlock Text="{Binding LastReceivedTime}"
Foreground="{StaticResource MutedTextBrush}"
FontSize="11" />
</StackPanel>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>

<Border Style="{StaticResource CardStyle}" Margin="0,0,0,0">
<StackPanel>
<TextBlock Text="Messenger 操作日志" Style="{StaticResource SubtleTitleStyle}" />
<ListBox ItemsSource="{Binding Logs}" Height="150" />
<TextBlock Style="{StaticResource HintTextStyle}"
Margin="0,9,0,0"
Text="观察方法:先让 B 反注册,再发送一条消息,B 的接收次数不会增加;重新注册 B 后,再发送一条,B 又会收到。" />
</StackPanel>
</Border>
</StackPanel>
</Grid>
</ScrollViewer>
</TabItem>

<TabItem Header="5 Messenger 双向">
<ScrollViewer VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Disabled">
<Grid x:Name="MessengerTwoWayRoot"
Margin="24,20,24,24"
DataContext="{Binding MessengerTwoWay}">
<StackPanel>
<TextBlock Text="5. Messenger双向委托调用"
Style="{StaticResource SectionTitleStyle}" />
<TextBlock Style="{StaticResource HintTextStyle}"
Text="双向不是指网络通信,而是两个对象互相持有对方的消息入口:A 发布消息触发 B 的委托,B 在委托中又能发布另一条消息触发 A 的委托。View 层也能通过同一条通道接收 VM 的请求。" />

<Border Style="{StaticResource CardStyle}" Margin="0,16,0,14">
<StackPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel>
<TextBlock Text="A 和 B 的往返消息" Style="{StaticResource SubtleTitleStyle}" />
<TextBlock Text="{Binding BStatusText}"
Foreground="{StaticResource MutedTextBrush}"
FontSize="12" />
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal">
<Button Content="自动往返一次"
Command="{Binding AutoRoundTripCommand}" />
<Button Content="{Binding ToggleBButtonText}"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding ToggleBCommand}" />
</StackPanel>
</Grid>
</StackPanel>
</Border>

<Grid Margin="0,0,0,14">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="104" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>

<Border Style="{StaticResource CardStyle}" Margin="0,0,0,0"
DataContext="{Binding PeerA}">
<StackPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" Style="{StaticResource SubtleTitleStyle}" />
<Border Grid.Column="1" Background="#E8F6EF" CornerRadius="10" Padding="8,3">
<TextBlock Text="{Binding RegisteredText}" Foreground="{StaticResource SuccessBrush}" FontSize="11" />
</Border>
</Grid>
<StackPanel Orientation="Horizontal" Margin="0,7,0,6">
<TextBlock Text="{Binding SentCountText}" Foreground="{StaticResource PrimaryBrush}" FontWeight="SemiBold" Margin="0,0,15,0" />
<TextBlock Text="{Binding ReceivedCountText}" Foreground="{StaticResource PrimaryBrush}" FontWeight="SemiBold" />
</StackPanel>
<TextBlock Text="{Binding LastAction}" Style="{StaticResource HintTextStyle}" MinHeight="42" />
<Button Content="{Binding SendButtonText}"
Command="{Binding SendCommand}"
HorizontalAlignment="Left" />
</StackPanel>
</Border>

<StackPanel Grid.Column="1" VerticalAlignment="Center">
<TextBlock Text="ToBMessage"
Foreground="{StaticResource PrimaryBrush}"
FontFamily="Consolas"
FontSize="11"
HorizontalAlignment="Center" />
<TextBlock Text="A → B"
Foreground="{StaticResource PrimaryDarkBrush}"
FontSize="19"
FontWeight="SemiBold"
HorizontalAlignment="Center"
Margin="0,3,0,10" />
<TextBlock Text="ToAMessage"
Foreground="{StaticResource PrimaryBrush}"
FontFamily="Consolas"
FontSize="11"
HorizontalAlignment="Center" />
<TextBlock Text="B → A"
Foreground="{StaticResource PrimaryDarkBrush}"
FontSize="19"
FontWeight="SemiBold"
HorizontalAlignment="Center"
Margin="0,3,0,0" />
</StackPanel>

<Border Grid.Column="2" Style="{StaticResource CardStyle}" Margin="0,0,0,0"
DataContext="{Binding PeerB}">
<StackPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Name}" Style="{StaticResource SubtleTitleStyle}" />
<Border Grid.Column="1" Background="#E8F6EF" CornerRadius="10" Padding="8,3">
<TextBlock Text="{Binding RegisteredText}" Foreground="{StaticResource SuccessBrush}" FontSize="11" />
</Border>
</Grid>
<StackPanel Orientation="Horizontal" Margin="0,7,0,6">
<TextBlock Text="{Binding SentCountText}" Foreground="{StaticResource PrimaryBrush}" FontWeight="SemiBold" Margin="0,0,15,0" />
<TextBlock Text="{Binding ReceivedCountText}" Foreground="{StaticResource PrimaryBrush}" FontWeight="SemiBold" />
</StackPanel>
<TextBlock Text="{Binding LastAction}" Style="{StaticResource HintTextStyle}" MinHeight="42" />
<Button Content="{Binding SendButtonText}"
Command="{Binding SendCommand}"
HorizontalAlignment="Left" />
</StackPanel>
</Border>
</Grid>

<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>

<Border Style="{StaticResource CardStyle}" Margin="0,0,12,0">
<StackPanel>
<TextBlock Text="VM → View:调用页面层方法" Style="{StaticResource SubtleTitleStyle}" />
<TextBlock Style="{StaticResource HintTextStyle}"
Text="按钮执行 ViewModel 命令,VM 发布 ShowViewMessage;窗口的代码隐藏文件注册了这个消息,收到后直接更新下面的文本。" />
<Border Background="#EAF4FC" CornerRadius="7" Padding="12,10" Margin="0,10,0,10">
<TextBlock x:Name="ViewCallResultText"
Text="等待 VM 发来消息"
Foreground="{StaticResource PrimaryDarkBrush}"
FontSize="13" />
</Border>
<Button Content="让 VM 调用页面层"
Command="{Binding CallViewCommand}"
HorizontalAlignment="Left" />
</StackPanel>
</Border>

<Border Grid.Column="1" Style="{StaticResource CardStyle}" Margin="0,0,0,0">
<StackPanel>
<TextBlock Text="双向调用日志" Style="{StaticResource SubtleTitleStyle}" />
<ListBox ItemsSource="{Binding Logs}" Height="150" />
</StackPanel>
</Border>
</Grid>
</StackPanel>
</Grid>
</ScrollViewer>
</TabItem>

<TabItem Header="6 DispatcherHelper">
<ScrollViewer VerticalScrollBarVisibility="Auto"
HorizontalScrollBarVisibility="Disabled">
<Grid x:Name="DispatcherRoot"
Margin="24,20,24,24"
DataContext="{Binding DispatcherDemo}">
<StackPanel>
<TextBlock Text="6. DispatcherHelper对象使用"
Style="{StaticResource SectionTitleStyle}" />
<TextBlock Style="{StaticResource HintTextStyle}"
Text="WPF 控件只允许创建它的界面线程访问。后台线程想更新进度条或文字时,必须把“更新动作”交回界面线程,DispatcherHelper 就是把这步写得更短的工具。" />

<Border Style="{StaticResource CardStyle}" Margin="0,16,0,14">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel>
<TextBlock Text="{Binding StatusText}" Style="{StaticResource SubtleTitleStyle}" />
<TextBlock Text="{Binding DispatcherReadyText}"
Foreground="{StaticResource SuccessBrush}"
FontSize="12" />
</StackPanel>
<StackPanel Grid.Column="1" Orientation="Horizontal" VerticalAlignment="Center">
<Button Content="开始后台任务"
Command="{Binding StartCommand}" />
<Button Content="检查初始化"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding CheckCommand}" />
<Button Content="重置演示"
Style="{StaticResource SecondaryButtonStyle}"
Command="{Binding ResetCommand}" />
</StackPanel>
</Grid>
</Border>

<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="48*" />
<ColumnDefinition Width="52*" />
</Grid.ColumnDefinitions>

<Border Style="{StaticResource CardStyle}" Margin="0,0,14,14">
<StackPanel>
<TextBlock Text="正确做法:交给 DispatcherHelper" Style="{StaticResource SubtleTitleStyle}" />
<TextBlock Text="{Binding ProgressText}"
Foreground="{StaticResource PrimaryDarkBrush}"
FontWeight="SemiBold"
Margin="0,8,0,6" />
<ProgressBar Value="{Binding Progress, Mode=OneWay}" Maximum="100" />
<TextBlock Text="{Binding BackgroundThreadText}"
Foreground="{StaticResource MutedTextBrush}"
FontSize="12"
Margin="0,10,0,3" />
<TextBlock FontSize="12" Foreground="{StaticResource MutedTextBrush}">
<Run Text="界面线程 ID:" />
<Run Text="{Binding UiThreadId, Mode=OneWay}" />
</TextBlock>
<TextBlock Style="{StaticResource HintTextStyle}"
Margin="0,10,0,0"
Text="后台线程不会直接碰控件,而是调用 CheckBeginInvokeOnUI,把更新动作排到界面线程执行。" />
</StackPanel>
</Border>

<Border Grid.Column="1" Style="{StaticResource CardStyle}" Margin="0,0,0,14">
<StackPanel>
<TextBlock Text="线程观察日志" Style="{StaticResource SubtleTitleStyle}" />
<ListBox ItemsSource="{Binding Logs}" Height="160" />
</StackPanel>
</Border>
</Grid>

<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>

<Border Style="{StaticResource CardStyle}" Margin="0,0,12,0">
<StackPanel>
<TextBlock Text="错误示范:后台线程直接改控件" Style="{StaticResource SubtleTitleStyle}" />
<TextBlock Style="{StaticResource HintTextStyle}"
Text="点击按钮后,后台线程会故意直接修改 TextBlock。WPF 会抛出“调用线程无法访问此对象”的异常,代码会捕获并显示异常类型。" />
<Border Background="#FFF1F1" CornerRadius="7" Padding="12,10" Margin="0,10,0,10">
<TextBlock x:Name="DispatcherProbeText"
Text="点击按钮观察结果"
Foreground="{StaticResource ErrorBrush}"
FontSize="12" />
</Border>
<Button Content="运行错误示范"
Style="{StaticResource SecondaryButtonStyle}"
Click="DirectUpdateButton_Click"
HorizontalAlignment="Left" />
</StackPanel>
</Border>

<Border Grid.Column="1" Style="{StaticResource CardStyle}" Margin="0,0,0,0">
<StackPanel>
<TextBlock Text="排查顺序" Style="{StaticResource SubtleTitleStyle}" />
<TextBlock Style="{StaticResource HintTextStyle}"
Text="1. 先确认 App 启动时执行了 DispatcherHelper.Initialize()。" />
<TextBlock Style="{StaticResource HintTextStyle}"
Text="2. 确认后台代码只修改 ViewModel 属性,不直接访问 TextBlock、Button 等控件。" />
<TextBlock Style="{StaticResource HintTextStyle}"
Text="3. 用 CheckBeginInvokeOnUI 包住界面更新,再观察日志中的线程 ID 是否回到界面线程。" />
</StackPanel>
</Border>
</Grid>
</StackPanel>
</Grid>
</ScrollViewer>
</TabItem>
</TabControl>
</Grid>

<Border Grid.Row="2" Background="#E8EEF5">
<Grid Margin="24,0">
<TextBlock Text="MvvmLight 入门之旅 · 示例项目 MvvmLightTour"
Foreground="{StaticResource MutedTextBrush}"
FontSize="11"
VerticalAlignment="Center" />
<TextBlock Text="命令行参数:--start-tab=1 到 6 · --self-test"
Foreground="{StaticResource MutedTextBrush}"
FontSize="11"
HorizontalAlignment="Right"
VerticalAlignment="Center" />
</Grid>
</Border>
</Grid>
</Window>
主窗口代码隐藏:MainWindow.xaml.cs
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Threading;
using MvvmLightTour.Infrastructure;
using MvvmLightTour.Messages;
using MvvmLightTour.ViewModels;

namespace MvvmLightTour
{
public partial class MainWindow : Window
{
private readonly MainViewModel _viewModel;
private bool _viewMessageRegistered;

public MainWindow()
{
InitializeComponent();
_viewModel = new MainViewModel();
DataContext = _viewModel;
ApplyStartupTab();
}

private async void Window_Loaded(object sender, RoutedEventArgs e)
{
if (Environment.GetCommandLineArgs().Any(argument => argument == "--self-test"))
{
Hide();
var passed = await SelfTestRunner.RunAsync();
Application.Current.Shutdown(passed ? 0 : 1);
return;
}

if (!_viewMessageRegistered)
{
Messenger.Default.Register<ShowViewMessage>(this, OnShowViewMessage);
_viewMessageRegistered = true;
}

string captureDirectory;
if (TryGetArgumentValue("--capture-dir=", out captureDirectory))
{
Height = 960;
UpdateLayout();
await Task.Delay(250);
await CaptureAllTabsAsync(captureDirectory);
Application.Current.Shutdown();
}
}

private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (_viewMessageRegistered)
{
Messenger.Default.Unregister<ShowViewMessage>(this);
_viewMessageRegistered = false;
}

_viewModel.Cleanup();
}

private void OnShowViewMessage(ShowViewMessage message)
{
ViewCallResultText.Text = message.Content;
ViewCallResultText.Foreground = new SolidColorBrush(Color.FromRgb(0x1E, 0x7B, 0x58));
}

private async void DirectUpdateButton_Click(object sender, RoutedEventArgs e)
{
DispatcherProbeText.Text = "后台线程准备直接修改控件...";
await Task.Run(() =>
{
try
{
DispatcherProbeText.Text = "如果看到这句话,说明跨线程更新没有按预期被拦截。";
}
catch (Exception exception)
{
DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
DispatcherProbeText.Text =
"已捕获 " + exception.GetType().Name + ":后台线程不能直接修改控件。";
});
}
});
}

private void ApplyStartupTab()
{
string value;
if (!TryGetArgumentValue("--start-tab=", out value))
{
return;
}

int tabNumber;
if (int.TryParse(value, out tabNumber) && tabNumber >= 1 && tabNumber <= 6)
{
_viewModel.SelectedTabIndex = tabNumber - 1;
TourTabs.SelectedIndex = tabNumber - 1;
}
}

private static bool TryGetArgumentValue(string prefix, out string value)
{
foreach (var argument in Environment.GetCommandLineArgs())
{
if (argument.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
{
value = argument.Substring(prefix.Length).Trim('"');
return !string.IsNullOrWhiteSpace(value);
}
}

value = null;
return false;
}

private async Task CaptureAllTabsAsync(string directory)
{
Directory.CreateDirectory(directory);
var fileNames = new[]
{
"01-framework-preparation.png",
"02-base-classes.png",
"03-command-objects.png",
"04-messenger-basic.png",
"05-messenger-two-way.png",
"06-dispatcher-helper.png"
};

for (var index = 0; index < fileNames.Length; index++)
{
TourTabs.SelectedIndex = index;
await Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ContextIdle);
await Task.Delay(250);
SaveVisualAsPng(
RootLayout,
Path.Combine(directory, fileNames[index]));
}

TourTabs.SelectedIndex = 5;
_viewModel.DispatcherDemo.StartCommand.Execute(null);
await Task.Delay(1500);
SaveVisualAsPng(
RootLayout,
Path.Combine(directory, "06b-dispatcher-running.png"));
}

private static void SaveVisualAsPng(FrameworkElement visual, string path)
{
visual.UpdateLayout();
var dpi = VisualTreeHelper.GetDpi(visual);
var width = Math.Max(1, (int)Math.Round(visual.ActualWidth * dpi.DpiScaleX));
var height = Math.Max(1, (int)Math.Round(visual.ActualHeight * dpi.DpiScaleY));
var bitmap = new RenderTargetBitmap(
width,
height,
96 * dpi.DpiScaleX,
96 * dpi.DpiScaleY,
PixelFormats.Pbgra32);
bitmap.Render(visual);

var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmap));
using (var stream = File.Create(path))
{
encoder.Save(stream);
}
}
}
}
消息类型:Messages/DemoMessages.cs
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
48
49
50
using System;

namespace MvvmLightTour.Messages
{
public class StatusMessage
{
public StatusMessage(string content)
{
Content = content;
SentAt = DateTime.Now;
}

public string Content { get; private set; }

public DateTime SentAt { get; private set; }
}

public class ToBMessage
{
public ToBMessage(string content, bool requestReply)
{
Content = content;
RequestReply = requestReply;
}

public string Content { get; private set; }

public bool RequestReply { get; private set; }
}

public class ToAMessage
{
public ToAMessage(string content)
{
Content = content;
}

public string Content { get; private set; }
}

public class ShowViewMessage
{
public ShowViewMessage(string content)
{
Content = content;
}

public string Content { get; private set; }
}
}
主 ViewModel:ViewModels/MainViewModel.cs
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
using GalaSoft.MvvmLight;

namespace MvvmLightTour.ViewModels
{
public class MainViewModel : ViewModelBase
{
private int _selectedTabIndex;

public MainViewModel()
{
Preparation = new PreparationViewModel();
BaseClasses = new BaseClassesViewModel();
CommandDemo = new CommandViewModel();
MessengerBasic = new MessengerBasicViewModel();
MessengerTwoWay = new MessengerTwoWayViewModel();
DispatcherDemo = new DispatcherHelperViewModel();
}

public PreparationViewModel Preparation { get; private set; }

public BaseClassesViewModel BaseClasses { get; private set; }

public CommandViewModel CommandDemo { get; private set; }

public MessengerBasicViewModel MessengerBasic { get; private set; }

public MessengerTwoWayViewModel MessengerTwoWay { get; private set; }

public DispatcherHelperViewModel DispatcherDemo { get; private set; }

public int SelectedTabIndex
{
get { return _selectedTabIndex; }
set { Set(ref _selectedTabIndex, value, nameof(SelectedTabIndex)); }
}

public override void Cleanup()
{
BaseClasses.Cleanup();
MessengerBasic.Cleanup();
MessengerTwoWay.Cleanup();
DispatcherDemo.Cleanup();
base.Cleanup();
}
}
}
第 1 章 ViewModel:ViewModels/PreparationViewModel.cs
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System;
using System.Threading;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Threading;

namespace MvvmLightTour.ViewModels
{
public class PreparationViewModel : ViewModelBase
{
private bool _isReady;
private string _environmentStatus;
private string _lastCheckTime;

public PreparationViewModel()
{
PackageVersion = typeof(ObservableObject).Assembly.GetName().Version.ToString();
RuntimeVersion = Environment.Version.ToString();
UiThreadId = Thread.CurrentThread.ManagedThreadId;

var frameworkName = AppDomain.CurrentDomain.SetupInformation.TargetFrameworkName;
TargetFramework = string.IsNullOrWhiteSpace(frameworkName)
? ".NET Framework 4.8"
: frameworkName.Replace(".NETFramework,Version=v", ".NET Framework ");

CheckEnvironmentCommand = new RelayCommand(CheckEnvironment);
CheckEnvironment();
}

public string PackageVersion { get; private set; }

public string TargetFramework { get; private set; }

public string RuntimeVersion { get; private set; }

public int UiThreadId { get; private set; }

public RelayCommand CheckEnvironmentCommand { get; private set; }

public bool IsReady
{
get { return _isReady; }
private set { Set(ref _isReady, value, nameof(IsReady)); }
}

public string EnvironmentStatus
{
get { return _environmentStatus; }
private set { Set(ref _environmentStatus, value, nameof(EnvironmentStatus)); }
}

public string LastCheckTime
{
get { return _lastCheckTime; }
private set { Set(ref _lastCheckTime, value, nameof(LastCheckTime)); }
}

private void CheckEnvironment()
{
var dispatcherReady = DispatcherHelper.UIDispatcher != null;
var assemblyReady = typeof(ObservableObject).Assembly != null;

IsReady = dispatcherReady && assemblyReady;
EnvironmentStatus = IsReady
? "环境检查通过:MvvmLight 程序集已加载,DispatcherHelper 已初始化。"
: "环境尚未就绪:请确认 App.OnStartup 中调用了 DispatcherHelper.Initialize()。";
LastCheckTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
}
}
}
第 2 章 ViewModel:ViewModels/BaseClassesViewModel.cs
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
using System.ComponentModel;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;

namespace MvvmLightTour.ViewModels
{
public class BaseClassesViewModel : ViewModelBase
{
private string _cleanupMessage;

public BaseClassesViewModel()
{
ManualCounter = new ManualCounter();
ObservableCounter = new ObservableCounter();
FrameworkCounter = new ViewModelCounter();
_cleanupMessage = "尚未执行 Cleanup()";

IncrementManualCommand = new RelayCommand(ManualCounter.Increase);
IncrementObservableCommand = new RelayCommand(ObservableCounter.Increase);
IncrementFrameworkCommand = new RelayCommand(FrameworkCounter.Increase);
CleanupCommand = new RelayCommand(CleanupFrameworkCounter);
ResetCommand = new RelayCommand(Reset);
}

public ManualCounter ManualCounter { get; private set; }

public ObservableCounter ObservableCounter { get; private set; }

public ViewModelCounter FrameworkCounter { get; private set; }

public RelayCommand IncrementManualCommand { get; private set; }

public RelayCommand IncrementObservableCommand { get; private set; }

public RelayCommand IncrementFrameworkCommand { get; private set; }

public RelayCommand CleanupCommand { get; private set; }

public RelayCommand ResetCommand { get; private set; }

public string CleanupMessage
{
get { return _cleanupMessage; }
private set { Set(ref _cleanupMessage, value, nameof(CleanupMessage)); }
}

private void CleanupFrameworkCounter()
{
FrameworkCounter.Cleanup();
CleanupMessage = FrameworkCounter.CleanupLog;
}

private void Reset()
{
ManualCounter.Reset();
ObservableCounter.Reset();
FrameworkCounter.Reset();
CleanupMessage = "尚未执行 Cleanup()";
}
}

public class ManualCounter : INotifyPropertyChanged
{
private int _count;

public event PropertyChangedEventHandler PropertyChanged;

public int Count
{
get { return _count; }
private set
{
if (_count == value)
{
return;
}

_count = value;
OnPropertyChanged(nameof(Count));
}
}

public void Increase()
{
Count++;
}

public void Reset()
{
Count = 0;
}

private void OnPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}

public class ObservableCounter : ObservableObject
{
private int _count;

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

public void Increase()
{
Count++;
}

public void Reset()
{
Count = 0;
}
}

public class ViewModelCounter : ViewModelBase
{
private int _count;
private string _cleanupLog;

public ViewModelCounter()
{
_cleanupLog = "尚未执行 Cleanup()";
}

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

public string CleanupLog
{
get { return _cleanupLog; }
private set { Set(ref _cleanupLog, value, nameof(CleanupLog)); }
}

public void Increase()
{
Count++;
}

public void Reset()
{
Count = 0;
CleanupLog = "尚未执行 Cleanup()";
}

public override void Cleanup()
{
CleanupLog = "Cleanup() 已执行:本页会在这里取消 Messenger 注册并释放资源。";
base.Cleanup();
}
}
}
第 3 章 ViewModel:ViewModels/CommandViewModel.cs
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
using System.Collections.ObjectModel;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;

namespace MvvmLightTour.ViewModels
{
public class CommandViewModel : ViewModelBase
{
private string _greeting;
private bool _allowSend;
private int _helloCount;
private int _numberTotal;

public CommandViewModel()
{
_greeting = "你好,MvvmLight";
_allowSend = true;
Logs = new ObservableCollection<string>();

SayHelloCommand = new RelayCommand(ExecuteSayHello, CanExecuteSayHello);
AddNumberCommand = new RelayCommand<string>(ExecuteAddNumber, CanExecuteAddNumber);
LockSendCommand = new RelayCommand(LockSend, () => AllowSend);
UnlockSendCommand = new RelayCommand(UnlockSend, () => !AllowSend);
ResetCommand = new RelayCommand(Reset);

AddLog("命令已创建:RelayCommand 负责发送,RelayCommand<string> 负责接收数字参数。");
}

public ObservableCollection<string> Logs { get; private set; }

public RelayCommand SayHelloCommand { get; private set; }

public RelayCommand<string> AddNumberCommand { get; private set; }

public RelayCommand LockSendCommand { get; private set; }

public RelayCommand UnlockSendCommand { get; private set; }

public RelayCommand ResetCommand { get; private set; }

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

public bool AllowSend
{
get { return _allowSend; }
private set
{
if (Set(ref _allowSend, value, nameof(AllowSend)))
{
RaiseStateProperties();
}
}
}

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

public int NumberTotal
{
get { return _numberTotal; }
private set
{
if (Set(ref _numberTotal, value, nameof(NumberTotal)))
{
RaisePropertyChanged(nameof(NumberTotalText));
RaisePropertyChanged(nameof(AddNumberStateText));
}
}
}

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

public string NumberTotalText
{
get { return "参数累计结果:" + NumberTotal; }
}

public string AllowSendText
{
get { return AllowSend ? "发送开关:已解锁" : "发送开关:已锁定"; }
}

public string CanExecuteText
{
get
{
return SayHelloCommand.CanExecute(null)
? "CanExecute = true,发送按钮可用"
: "CanExecute = false,发送按钮已禁用";
}
}

public string AddNumberStateText
{
get
{
return AddNumberCommand.CanExecute("1")
? "RelayCommand<string> 仍可继续累加"
: "累计结果已达到 100,参数命令已禁用";
}
}

private void ExecuteSayHello()
{
HelloCount++;
AddLog("执行 SayHelloCommand:" + Greeting);
}

private bool CanExecuteSayHello()
{
return AllowSend && !string.IsNullOrWhiteSpace(Greeting);
}

private void ExecuteAddNumber(string parameter)
{
int value;
if (!int.TryParse(parameter, out value))
{
AddLog("参数无法转换为整数,命令没有执行。");
return;
}

NumberTotal += value;
AddLog("RelayCommand<string> 收到参数 " + value + ",累计结果变为 " + NumberTotal + "。");
AddNumberCommand.RaiseCanExecuteChanged();
}

private bool CanExecuteAddNumber(string parameter)
{
int value;
return int.TryParse(parameter, out value) && NumberTotal + value <= 100;
}

private void LockSend()
{
AllowSend = false;
AddLog("发送开关已锁定,SayHelloCommand 的 CanExecute 返回 false。");
LockSendCommand.RaiseCanExecuteChanged();
UnlockSendCommand.RaiseCanExecuteChanged();
}

private void UnlockSend()
{
AllowSend = true;
AddLog("发送开关已解锁,SayHelloCommand 重新可用。");
LockSendCommand.RaiseCanExecuteChanged();
UnlockSendCommand.RaiseCanExecuteChanged();
}

private void Reset()
{
HelloCount = 0;
NumberTotal = 0;
AllowSend = true;
Logs.Clear();
AddLog("演示已重置。输入框、累计值和命令状态都回到了初始状态。");
SayHelloCommand.RaiseCanExecuteChanged();
AddNumberCommand.RaiseCanExecuteChanged();
LockSendCommand.RaiseCanExecuteChanged();
UnlockSendCommand.RaiseCanExecuteChanged();
}

private void RaiseStateProperties()
{
RaisePropertyChanged(nameof(HelloCountText));
RaisePropertyChanged(nameof(NumberTotalText));
RaisePropertyChanged(nameof(AllowSendText));
RaisePropertyChanged(nameof(CanExecuteText));
RaisePropertyChanged(nameof(AddNumberStateText));
SayHelloCommand.RaiseCanExecuteChanged();
AddNumberCommand.RaiseCanExecuteChanged();
}

private void AddLog(string message)
{
Logs.Add(message);
while (Logs.Count > 20)
{
Logs.RemoveAt(0);
}
}
}
}
第 4 章 ViewModel:ViewModels/MessengerBasicViewModel.cs
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
using System;
using System.Collections.ObjectModel;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Messaging;
using MvvmLightTour.Messages;

namespace MvvmLightTour.ViewModels
{
public class MessageListener : ObservableObject
{
private string _lastMessage;
private string _lastReceivedTime;
private int _receivedCount;
private bool _isRegistered;

public MessageListener(string name)
{
Name = name;
_lastMessage = "尚未收到消息";
_lastReceivedTime = "--";
}

public string Name { get; private set; }

public string LastMessage
{
get { return _lastMessage; }
private set { Set(ref _lastMessage, value, nameof(LastMessage)); }
}

public string LastReceivedTime
{
get { return _lastReceivedTime; }
private set { Set(ref _lastReceivedTime, value, nameof(LastReceivedTime)); }
}

public int ReceivedCount
{
get { return _receivedCount; }
private set
{
if (Set(ref _receivedCount, value, nameof(ReceivedCount)))
{
RaisePropertyChanged(nameof(ReceivedCountText));
}
}
}

public bool IsRegistered
{
get { return _isRegistered; }
private set
{
if (Set(ref _isRegistered, value, nameof(IsRegistered)))
{
RaisePropertyChanged(nameof(RegisteredText));
}
}
}

public string ReceivedCountText
{
get { return "收到 " + ReceivedCount + " 条"; }
}

public string RegisteredText
{
get { return IsRegistered ? "已注册" : "已反注册"; }
}

public void Receive(StatusMessage message)
{
LastMessage = message.Content;
LastReceivedTime = message.SentAt.ToString("HH:mm:ss");
ReceivedCount++;
}

public void SetRegistration(bool isRegistered)
{
IsRegistered = isRegistered;
}
}

public class MessengerBasicViewModel : ViewModelBase
{
private readonly IMessenger _messenger;
private string _draft;
private int _messageNumber;

public MessengerBasicViewModel()
: this(Messenger.Default)
{
}

public MessengerBasicViewModel(IMessenger messenger)
{
_messenger = messenger;
_draft = "这是一条广播消息";
Logs = new ObservableCollection<string>();
Listeners = new ObservableCollection<MessageListener>
{
new MessageListener("监听器 A"),
new MessageListener("监听器 B"),
new MessageListener("监听器 C")
};

SendMessageCommand = new RelayCommand(SendMessage);
RegisterAllCommand = new RelayCommand(RegisterAll);
RegisterBCommand = new RelayCommand(RegisterB, () => !BListener.IsRegistered);
UnregisterBCommand = new RelayCommand(UnregisterB, () => BListener.IsRegistered);

RegisterAll();
SendMessage();
}

public ObservableCollection<MessageListener> Listeners { get; private set; }

public ObservableCollection<string> Logs { get; private set; }

public RelayCommand SendMessageCommand { get; private set; }

public RelayCommand RegisterAllCommand { get; private set; }

public RelayCommand RegisterBCommand { get; private set; }

public RelayCommand UnregisterBCommand { get; private set; }

public MessageListener BListener
{
get { return Listeners[1]; }
}

public string Draft
{
get { return _draft; }
set { Set(ref _draft, value, nameof(Draft)); }
}

public string BStatusText
{
get { return BListener.IsRegistered ? "B 正在监听消息" : "B 已反注册,收不到新消息"; }
}

private void RegisterAll()
{
var registeredNow = 0;
foreach (var listener in Listeners)
{
if (listener.IsRegistered)
{
continue;
}

_messenger.Register<StatusMessage>(listener, listener.Receive);
listener.SetRegistration(true);
registeredNow++;
AddLog(listener.Name + " 调用 Register<StatusMessage> 完成注册。");
}

if (registeredNow == 0)
{
AddLog("所有监听器都已经处于注册状态。");
}

RefreshBCommands();
}

private void RegisterB()
{
if (BListener.IsRegistered)
{
return;
}

_messenger.Register<StatusMessage>(BListener, BListener.Receive);
BListener.SetRegistration(true);
AddLog("监听器 B 重新注册,之后会继续收到 StatusMessage。");
RefreshBCommands();
}

private void UnregisterB()
{
if (!BListener.IsRegistered)
{
return;
}

_messenger.Unregister<StatusMessage>(BListener);
BListener.SetRegistration(false);
AddLog("监听器 B 调用 Unregister<StatusMessage>,不再收到后续消息。");
RefreshBCommands();
}

private void SendMessage()
{
_messageNumber++;
var content = string.IsNullOrWhiteSpace(Draft)
? "第 " + _messageNumber + " 条消息"
: "第 " + _messageNumber + " 条:" + Draft.Trim();

_messenger.Send(new StatusMessage(content));
AddLog("发布 StatusMessage:" + content);
}

private void RefreshBCommands()
{
RaisePropertyChanged(nameof(BStatusText));
RegisterBCommand.RaiseCanExecuteChanged();
UnregisterBCommand.RaiseCanExecuteChanged();
}

private void AddLog(string message)
{
Logs.Add(message);
while (Logs.Count > 20)
{
Logs.RemoveAt(0);
}
}

public override void Cleanup()
{
foreach (var listener in Listeners)
{
if (listener.IsRegistered)
{
_messenger.Unregister<StatusMessage>(listener);
listener.SetRegistration(false);
}
}

base.Cleanup();
}
}
}
第 5 章 ViewModel:ViewModels/MessengerTwoWayViewModel.cs
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
using System;
using System.Collections.ObjectModel;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Messaging;
using MvvmLightTour.Messages;

namespace MvvmLightTour.ViewModels
{
public class MessengerPeer : ObservableObject
{
private readonly IMessenger _messenger;
private readonly bool _isA;
private readonly Action<string> _log;
private int _sentCount;
private int _receivedCount;
private string _lastAction;
private bool _isRegistered;

public MessengerPeer(string name, bool isA, IMessenger messenger, Action<string> log)
{
Name = name;
_isA = isA;
_messenger = messenger;
_log = log;
_lastAction = "等待操作";
SendCommand = new RelayCommand(Send);
}

public string Name { get; private set; }

public RelayCommand SendCommand { get; private set; }

public int SentCount
{
get { return _sentCount; }
private set
{
if (Set(ref _sentCount, value, nameof(SentCount)))
{
RaisePropertyChanged(nameof(SentCountText));
}
}
}

public int ReceivedCount
{
get { return _receivedCount; }
private set
{
if (Set(ref _receivedCount, value, nameof(ReceivedCount)))
{
RaisePropertyChanged(nameof(ReceivedCountText));
}
}
}

public string LastAction
{
get { return _lastAction; }
private set { Set(ref _lastAction, value, nameof(LastAction)); }
}

public bool IsRegistered
{
get { return _isRegistered; }
private set
{
if (Set(ref _isRegistered, value, nameof(IsRegistered)))
{
RaisePropertyChanged(nameof(RegisteredText));
}
}
}

public string SentCountText
{
get { return "发送 " + SentCount + " 条"; }
}

public string ReceivedCountText
{
get { return "接收 " + ReceivedCount + " 条"; }
}

public string RegisteredText
{
get { return IsRegistered ? "已注册" : "已反注册"; }
}

public string SendButtonText
{
get { return _isA ? "A 向 B 发送并请求回复" : "B 向 A 发送消息"; }
}

public void Register()
{
if (IsRegistered)
{
return;
}

if (_isA)
{
_messenger.Register<ToAMessage>(this, ReceiveToA);
}
else
{
_messenger.Register<ToBMessage>(this, ReceiveToB);
}

IsRegistered = true;
_log(Name + " 已注册,准备接收" + (_isA ? " ToAMessage。" : " ToBMessage。"));
}

public void Unregister()
{
if (!IsRegistered)
{
return;
}

if (_isA)
{
_messenger.Unregister<ToAMessage>(this);
}
else
{
_messenger.Unregister<ToBMessage>(this);
}

IsRegistered = false;
_log(Name + " 已反注册,新的消息不会再进入它的委托方法。");
}

private void Send()
{
if (_isA)
{
_messenger.Send(new ToBMessage("你好,B。请收到后回复我。", true));
SentCount++;
LastAction = "已发送 ToBMessage,并请求 B 回复";
_log("A 发布 ToBMessage,等待 B 的接收委托执行。");
}
else
{
_messenger.Send(new ToAMessage("你好,A。这是 B 主动发来的消息。"));
SentCount++;
LastAction = "已发送 ToAMessage";
_log("B 发布 ToAMessage,等待 A 的接收委托执行。");
}
}

private void ReceiveToB(ToBMessage message)
{
ReceivedCount++;
LastAction = "收到 A:" + message.Content;
_log("B 收到 ToBMessage:" + message.Content);

if (message.RequestReply)
{
_messenger.Send(new ToAMessage("收到,我是 B。这是一次自动回复。"));
SentCount++;
LastAction = "已自动回复 A";
_log("B 在接收委托中发布 ToAMessage,形成一次往返调用。");
}
}

private void ReceiveToA(ToAMessage message)
{
ReceivedCount++;
LastAction = "收到 B:" + message.Content;
_log("A 收到 ToAMessage:" + message.Content);
}
}

public class MessengerTwoWayViewModel : ViewModelBase
{
private readonly IMessenger _messenger;

public MessengerTwoWayViewModel()
: this(Messenger.Default)
{
}

public MessengerTwoWayViewModel(IMessenger messenger)
{
_messenger = messenger;
Logs = new ObservableCollection<string>();

PeerA = new MessengerPeer("对象 A", true, messenger, AddLog);
PeerB = new MessengerPeer("对象 B", false, messenger, AddLog);
PeerA.Register();
PeerB.Register();

AutoRoundTripCommand = new RelayCommand(
() => PeerA.SendCommand.Execute(null),
() => PeerB.IsRegistered);
ToggleBCommand = new RelayCommand(ToggleB);
CallViewCommand = new RelayCommand(CallView);

PeerA.SendCommand.Execute(null);
}

public ObservableCollection<string> Logs { get; private set; }

public MessengerPeer PeerA { get; private set; }

public MessengerPeer PeerB { get; private set; }

public RelayCommand AutoRoundTripCommand { get; private set; }

public RelayCommand ToggleBCommand { get; private set; }

public RelayCommand CallViewCommand { get; private set; }

public string ToggleBButtonText
{
get { return PeerB.IsRegistered ? "让 B 反注册" : "重新注册 B"; }
}

public string BStatusText
{
get { return PeerB.IsRegistered ? "B 的委托已挂到 Messenger" : "B 已反注册,自动回复会停止"; }
}

private void ToggleB()
{
if (PeerB.IsRegistered)
{
PeerB.Unregister();
}
else
{
PeerB.Register();
}

RaisePropertyChanged(nameof(ToggleBButtonText));
RaisePropertyChanged(nameof(BStatusText));
AutoRoundTripCommand.RaiseCanExecuteChanged();
}

private void CallView()
{
var content = "页面层方法已被 VM 调用,时间 " + DateTime.Now.ToString("HH:mm:ss") + "。";
_messenger.Send(new ShowViewMessage(content));
AddLog("VM 发布 ShowViewMessage,等待 View 的代码隐藏文件接收。");
}

private void AddLog(string message)
{
Logs.Add(message);
while (Logs.Count > 24)
{
Logs.RemoveAt(0);
}
}

public override void Cleanup()
{
PeerA.Unregister();
PeerB.Unregister();
base.Cleanup();
}
}
}
第 6 章 ViewModel:ViewModels/DispatcherHelperViewModel.cs
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
using System;
using System.Collections.ObjectModel;
using System.Threading;
using System.Threading.Tasks;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Threading;

namespace MvvmLightTour.ViewModels
{
public class DispatcherHelperViewModel : ViewModelBase
{
private bool _isRunning;
private bool _isCancelled;
private int _progress;
private int _backgroundThreadId;
private string _statusText;

public DispatcherHelperViewModel()
{
UiThreadId = Thread.CurrentThread.ManagedThreadId;
_statusText = "等待开始后台任务";
Logs = new ObservableCollection<string>();

StartCommand = new RelayCommand(StartWork, () => !IsRunning);
ResetCommand = new RelayCommand(Reset, () => !IsRunning);
CheckCommand = new RelayCommand(CheckInitialization);

AddLog("DispatcherHelper 初始化状态:" + (DispatcherHelper.UIDispatcher != null ? "已初始化" : "未初始化"));
AddLog("当前界面线程 ID:" + UiThreadId);
}

public ObservableCollection<string> Logs { get; private set; }

public RelayCommand StartCommand { get; private set; }

public RelayCommand ResetCommand { get; private set; }

public RelayCommand CheckCommand { get; private set; }

public int UiThreadId { get; private set; }

public int BackgroundThreadId
{
get { return _backgroundThreadId; }
private set
{
if (Set(ref _backgroundThreadId, value, nameof(BackgroundThreadId)))
{
RaisePropertyChanged(nameof(BackgroundThreadText));
}
}
}

public int Progress
{
get { return _progress; }
private set
{
if (Set(ref _progress, value, nameof(Progress)))
{
RaisePropertyChanged(nameof(ProgressText));
}
}
}

public bool IsRunning
{
get { return _isRunning; }
private set
{
if (Set(ref _isRunning, value, nameof(IsRunning)))
{
StartCommand.RaiseCanExecuteChanged();
ResetCommand.RaiseCanExecuteChanged();
}
}
}

public string StatusText
{
get { return _statusText; }
private set { Set(ref _statusText, value, nameof(StatusText)); }
}

public string BackgroundThreadText
{
get
{
return BackgroundThreadId == 0
? "后台线程 ID:尚未启动"
: "后台线程 ID:" + BackgroundThreadId;
}
}

public string ProgressText
{
get { return "当前进度:" + Progress + "%"; }
}

public string DispatcherReadyText
{
get
{
return DispatcherHelper.UIDispatcher == null
? "DispatcherHelper:未初始化"
: "DispatcherHelper:已初始化";
}
}

private void StartWork()
{
if (IsRunning)
{
return;
}

IsRunning = true;
Progress = 0;
BackgroundThreadId = 0;
StatusText = "后台任务正在运行";
AddLog("点击按钮发生在界面线程 " + Thread.CurrentThread.ManagedThreadId + "。");
Task.Run(() => RunBackgroundWork());
}

private void RunBackgroundWork()
{
var workerThreadId = Thread.CurrentThread.ManagedThreadId;
DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
BackgroundThreadId = workerThreadId;
AddLog("后台线程 " + workerThreadId + " 已启动。");
});

for (var step = 1; step <= 10; step++)
{
if (_isCancelled)
{
return;
}

Thread.Sleep(140);
var value = step * 10;
DispatcherHelper.CheckBeginInvokeOnUI(() =>
{
Progress = value;
AddLog("界面线程 " + Thread.CurrentThread.ManagedThreadId + " 更新进度为 " + value + "%。");

if (value == 100)
{
IsRunning = false;
StatusText = "后台任务完成,界面更新成功";
AddLog("后台任务结束,所有界面更新都通过 DispatcherHelper 完成。");
}
});
}
}

private void Reset()
{
if (IsRunning)
{
return;
}

Progress = 0;
BackgroundThreadId = 0;
StatusText = "演示已重置,等待开始";
Logs.Clear();
AddLog("演示已重置。");
AddLog("DispatcherHelper 初始化状态:" + (DispatcherHelper.UIDispatcher != null ? "已初始化" : "未初始化"));
AddLog("当前界面线程 ID:" + UiThreadId);
}

private void CheckInitialization()
{
var ready = DispatcherHelper.UIDispatcher != null;
StatusText = ready ? "检查通过:DispatcherHelper 已初始化" : "检查失败:请先调用 DispatcherHelper.Initialize()";
AddLog("执行初始化检查,结果:" + (ready ? "已初始化" : "未初始化"));
RaisePropertyChanged(nameof(DispatcherReadyText));
}

private void AddLog(string message)
{
Logs.Add(message);
while (Logs.Count > 24)
{
Logs.RemoveAt(0);
}
}

public override void Cleanup()
{
_isCancelled = true;
base.Cleanup();
}
}
}
自测入口:Infrastructure/SelfTestRunner.cs
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.CommandWpf;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Threading;
using MvvmLightTour.Messages;
using MvvmLightTour.ViewModels;

namespace MvvmLightTour.Infrastructure
{
public static class SelfTestRunner
{
public static async Task<bool> RunAsync()
{
var lines = new List<string>();
var errors = new List<string>();

void Check(string name, Action test)
{
try
{
test();
lines.Add("通过 | " + name);
}
catch (Exception exception)
{
lines.Add("失败 | " + name + " | " + exception.Message);
errors.Add(name + Environment.NewLine + exception);
}
}

Check("INotifyPropertyChanged 手工实现能触发通知", () =>
{
var counter = new ManualCounter();
var notified = false;
PropertyChangedEventHandler handler = (sender, args) =>
{
if (args.PropertyName == nameof(ManualCounter.Count))
{
notified = true;
}
};

counter.PropertyChanged += handler;
counter.Increase();
counter.PropertyChanged -= handler;

if (!notified || counter.Count != 1)
{
throw new InvalidOperationException("手工计数器没有正确发出属性变更通知。");
}
});

Check("ObservableObject.Set 能更新属性", () =>
{
var counter = new ObservableCounter();
counter.Increase();
if (counter.Count != 1)
{
throw new InvalidOperationException("ObservableObject 计数器的值不正确。");
}
});

Check("ViewModelBase.Cleanup 可被重写", () =>
{
var counter = new ViewModelCounter();
counter.Cleanup();
if (!counter.CleanupLog.Contains("已执行"))
{
throw new InvalidOperationException("ViewModelBase.Cleanup 没有被正确执行。");
}
});

Check("RelayCommand 的 Execute 和 CanExecute", () =>
{
var canExecute = true;
var executed = 0;
var command = new RelayCommand(() => executed++, () => canExecute);

if (!command.CanExecute(null))
{
throw new InvalidOperationException("RelayCommand 初始状态应可执行。");
}

command.Execute(null);
canExecute = false;
command.RaiseCanExecuteChanged();

if (executed != 1 || command.CanExecute(null))
{
throw new InvalidOperationException("RelayCommand 的执行或禁用状态不正确。");
}
});

Check("RelayCommand<string> 能接收参数", () =>
{
var viewModel = new CommandViewModel();
viewModel.AddNumberCommand.Execute("5");
if (viewModel.NumberTotal != 5)
{
throw new InvalidOperationException("RelayCommand<string> 没有正确接收参数 5。");
}
});

Check("Messenger 注册、发送和反注册", () =>
{
var messenger = new Messenger();
var listener = new MessageListener("测试监听器");
messenger.Register<StatusMessage>(listener, listener.Receive);
messenger.Send(new StatusMessage("第一条测试消息"));

if (listener.ReceivedCount != 1)
{
throw new InvalidOperationException("Messenger 注册后没有收到消息。");
}

messenger.Unregister<StatusMessage>(listener);
messenger.Send(new StatusMessage("第二条测试消息"));

if (listener.ReceivedCount != 1)
{
throw new InvalidOperationException("反注册后仍然收到了消息。");
}
});

Check("Messenger 双向委托调用", () =>
{
var messenger = new Messenger();
var viewModel = new MessengerTwoWayViewModel(messenger);
var aSentBefore = viewModel.PeerA.SentCount;
var bReceivedBefore = viewModel.PeerB.ReceivedCount;
viewModel.AutoRoundTripCommand.Execute(null);

if (viewModel.PeerA.SentCount <= aSentBefore ||
viewModel.PeerB.ReceivedCount <= bReceivedBefore ||
viewModel.PeerA.ReceivedCount == 0)
{
throw new InvalidOperationException("双向消息没有完整往返。");
}

viewModel.Cleanup();
});

Check("Preparation 环境检查", () =>
{
var viewModel = new PreparationViewModel();
viewModel.CheckEnvironmentCommand.Execute(null);
if (!viewModel.IsReady)
{
throw new InvalidOperationException("准备页环境检查没有通过。");
}
});

try
{
var uiThreadId = Thread.CurrentThread.ManagedThreadId;
var completion = new TaskCompletionSource<int>();
_ = Task.Run(() =>
{
DispatcherHelper.CheckBeginInvokeOnUI(
() => completion.TrySetResult(Thread.CurrentThread.ManagedThreadId));
});

var winner = await Task.WhenAny(completion.Task, Task.Delay(3000));
if (winner != completion.Task)
{
throw new TimeoutException("等待 DispatcherHelper 回调超时。");
}

var callbackThreadId = await completion.Task;
if (callbackThreadId != uiThreadId)
{
throw new InvalidOperationException(
"DispatcherHelper 回调线程为 " + callbackThreadId + ",界面线程为 " + uiThreadId + "。");
}

lines.Add("通过 | DispatcherHelper 能把后台回调切回界面线程");
}
catch (Exception exception)
{
lines.Add("失败 | DispatcherHelper 能把后台回调切回界面线程 | " + exception.Message);
errors.Add("DispatcherHelper 跨线程测试" + Environment.NewLine + exception);
}

var passed = errors.Count == 0;
var builder = new StringBuilder();
builder.AppendLine("MvvmLightTour 自测结果");
builder.AppendLine("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
builder.AppendLine("结果:" + (passed ? "全部通过" : "存在失败项"));
builder.AppendLine("检查项:" + lines.Count);
builder.AppendLine();
foreach (var line in lines)
{
builder.AppendLine(line);
}

var outputDirectory = Environment.CurrentDirectory;
var outputPath = Path.Combine(outputDirectory, "self-test-result.txt");
File.WriteAllText(outputPath, builder.ToString(), new UTF8Encoding(false));

if (!passed)
{
var logDirectory = Path.Combine(outputDirectory, "logs");
Directory.CreateDirectory(logDirectory);
File.WriteAllText(
Path.Combine(logDirectory, "self-test-error.log"),
string.Join(Environment.NewLine + Environment.NewLine, errors),
new UTF8Encoding(false));
}

return passed;
}
}
}