这份笔记按你给的目录写成 6 章:

  1. CommunityToolkit了解与基本使用
  2. CommunityToolkit中的可观察对象与通知属性
  3. CommunityToolkit中的命令对象与IoC使用
  4. CommunityToolkit中的通知属性特性使用
  5. CommunityToolkit中的命令与验证特性使用
  6. CommunityToolkit中的异步命令与消息接口

你提供的参考代码已经读取并构建过。参考项目是:

1
2
3
E:\学习资料\上位机学习\WPF第4期\20250929WPF上位机04Course042CommunityToolkit
\20250929WPF上位机04Course042CommunityToolkit\src\Zhaoxi.MvvmLightLesson
\Zhaoxi.MvvmToolkit.Lesson

参考代码能构建通过,但有 net7.0-windows 已停止支持的警告,以及一些可空引用警告。这份笔记不照搬它的大 MainViewModel,而是把通知属性、命令、IoC、特性、验证、异步命令和消息拆成 6 个页面,方便一章只学一个点。

全书思维主线

这份笔记不只教你“代码怎么写”,更希望你能带走一套判断方法。每一章表面上学的是不同工具,背后其实都在训练同一种能力:先看清对象之间的关系,再决定代码放在哪里。

章节 表面上学什么 真正要学的思维 遇到新问题时先问
1 ObservableObject、DataContext、绑定 界面和状态分开 这个数据应该由谁保存?界面只是显示吗?
2 [ObservableProperty] 状态变化要能被界面看见 哪些值是运行中会变的?变了要通知谁?
3 [RelayCommand]、IoC 声明依赖,集中装配 谁需要谁?谁负责创建?
4 [NotifyPropertyChangedFor] 状态之间有依赖,变化会传播 这个值变了,还有哪些显示会受影响?
5 验证特性、CanExecute 规则决定状态,状态决定按钮 什么算合法?按钮什么时候可用?
6 异步命令、Messenger 耗时任务要管理过程,完成通知要解耦 任务多久?完成后谁关心?失败怎么显示?

读每一章时,先看“一句话原理”和“本章真正要学的思维”,再动手写。代码只是思维的结果,不要反过来死记代码。

参考代码和推荐写法

参考代码里的做法 本笔记的推荐写法 为什么调整
一个 MainViewModel 同时放属性、命令、验证和消息 每章一个独立 ViewModel 初学时一次只看一个概念,报错也更容易定位
App.Service 直接暴露容器 App.Services + GetRequiredService<T>() 让“取对象”的位置更明确
在 ViewModel 里直接 new UserEntity() 只保留当前章节需要的字段 减少无关代码,先理解主线
先写完整类再运行 每章先写最小界面,再写最小代码,再运行 符合你要求的循序渐进

环境与项目

项目 本示例
IDE Visual Studio 2022 或命令行
目标框架 .NET 7 的 WPF:net7.0-windows
MVVM 包 CommunityToolkit.Mvvm 8.2.1
IoC 包 Microsoft.Extensions.DependencyInjection 7.0.0
示例项目 示例代码/CommunityToolkitDemo/CommunityToolkitDemo.csproj
自测项目 示例代码/CommunityToolkitDemo.Tests/CommunityToolkitDemo.Tests.csproj

net7.0-windows 是按你参考项目的版本保留的。实际新项目可以升级到当前仍受支持的 .NET 版本;本笔记不把版本升级混进教学主线。

运行方式

在 C:\Users\North\Desktop\WPFStudy 打开 PowerShell:

1
dotnet run --project .\示例代码\CommunityToolkitDemo\CommunityToolkitDemo.csproj -c Release

如果想先验证 ViewModel 的行为,不打开窗口,可以运行:

1
dotnet run --project .\示例代码\CommunityToolkitDemo.Tests\CommunityToolkitDemo.Tests.csproj -c Release

本次实际自测输出:

1
2
3
4
5
6
7
8
9
10
可观察属性:你好,小红
命令与 IoC:你好,小明!这条消息来自 IoC 注入的服务。
属性特性:李四
验证初始可提交:True
空值可提交:False
空值错误:姓名不能为空
合法值可提交:True
提交结果:提交成功:小明
异步命令状态:加载完成
消息接收结果:后台任务已经完成

项目结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
CommunityToolkitDemo
├─ CommunityToolkitDemo.csproj
├─ App.xaml
├─ App.xaml.cs
├─ MainWindow.xaml
├─ MainWindow.xaml.cs
├─ Messages/
│ └─ StatusMessage.cs
├─ Services/
│ ├─ IGreetingService.cs
│ └─ GreetingService.cs
└─ ViewModels/
├─ MainViewModel.cs
├─ PreparationViewModel.cs
├─ ObservableDemoViewModel.cs
├─ CommandIocViewModel.cs
├─ PropertyAttributesViewModel.cs
├─ ValidationViewModel.cs
└─ AsyncMessageViewModel.cs

Messages 放消息类型,Services 放可注入的服务,ViewModels 放页面逻辑,App.xaml.cs 负责注册,MainWindow 只负责把界面和 ViewModel 接起来。

读法说明:=> 与 Lambda

这份笔记后面会反复出现 =>。你先不要把它当成一个符号死记,先看它左边是谁:

你看到的写法 先这样读
public string PackageInfo => "..."; 只读属性;每次读取时返回右边的内容
get => _status; getter 只有一句 return _status;
set => SetProperty(...); setter 只有一句调用
error => error.ErrorMessage Lambda:对每一个 error,取出它的 ErrorMessage
(_, _) => OnPropertyChanged(...) Lambda:两个参数都不使用,事件触发时执行右边
() => new MessageService() Lambda:没有参数,调用时创建一个新对象

1. 表达式体属性

public string PackageInfo => "CommunityToolkit.Mvvm 8.2.1"; 里的 => 不是 Lambda,因为左边是属性名。它是“表达式体属性”的简写,等价于:

1
2
3
4
public string PackageInfo
{
get { return "CommunityToolkit.Mvvm 8.2.1"; }
}

因为它只有 get,没有 set,所以它是只读属性。界面可以读取它,但不能通过绑定把它改掉。

同样,下面两行也是表达式体写法:

1
2
3
4
5
public string Status
{
get => _status;
set => SetProperty(ref _status, value);
}

它等价于:

1
2
3
4
5
public string Status
{
get { return _status; }
set { SetProperty(ref _status, value); }
}

2. Lambda

Lambda 的样子是“参数 => 表达式”。左边的 error、_ 或空括号是参数,右边是要执行的内容。

1
GetErrors().Select(error => error.ErrorMessage)

可以读成:“把 GetErrors() 里的每一个 error 拿出来,分别返回它的 ErrorMessage。”Select 会把每个返回值收集成一个新的序列。

1
ErrorsChanged += (_, _) => OnPropertyChanged(nameof(ErrorMessage));

可以读成:“当 ErrorsChanged 事件发生时,执行右边的 OnPropertyChanged(...)。”这里的两个 _ 表示“这两个参数我暂时不用”,不是变量名。

记住一个判断方法:左边是属性名、get 或 set,通常是表达式体成员;左边是参数、括号或空括号,通常是 Lambda。


1. CommunityToolkit了解与基本使用

1. 本节目标

创建一个能运行的 WPF 项目,安装 CommunityToolkit.Mvvm,并在第一个页签里看到包信息和一段状态文字。

做完后应该看到:

1
2
CommunityToolkit.Mvvm 8.2.1
CommunityToolkit.Mvvm 已就绪

2. 一句话原理

CommunityToolkit.Mvvm 不是一个完整的应用框架,而是一盒常用的 MVVM 工具:属性通知、命令、消息、验证和异步命令都在里面。

你可以把它想成一个工具箱:项目还是你的 WPF 项目,工具箱只是让你少写重复代码。

本章真正要学的思维:界面只负责显示,状态由 ViewModel 提供。

  • 以前的写法:在按钮点击事件里直接改 TextBlock.Text。
  • MVVM 的写法:ViewModel 保存 Status,XAML 用 {Binding Status} 读取。
  • 判断方法:看到界面上的文字、开关、列表,先问“它对应 ViewModel 里的哪个状态属性?”
  • 迁移到其他框架:不管界面是 WPF、WinForms 还是网页,都可以把“显示”和“状态”分开。界面只是状态的一种投影。

3. 要改哪里

顺序 文件 位置 要做什么
1 CommunityToolkitDemo.csproj ItemGroup 安装 CommunityToolkit.Mvvm
2 ViewModels/PreparationViewModel.cs PreparationViewModel 类 写两个只读文字属性
3 MainWindow.xaml 第一个 TabItem 显示包信息和状态
4 MainWindow.xaml.cs 构造函数 先把 DataContext 设为准备页 ViewModel

4. 第一步:写最小界面

新建 WPF 项目后,先把 MainWindow.xaml 里的内容换成一个简单的 TabControl。这一章只放第一个页签,不急着把所有章节一次写完。

打开 MainWindow.xaml,把 Grid 里的内容改成:

1
2
3
4
5
6
7
8
9
10
11
12
<TabControl Margin="20">
<TabItem Header="1 基本使用">
<StackPanel Margin="24">
<TextBlock Text="CommunityToolkit.Mvvm 基本使用"
FontSize="26" FontWeight="Bold" />
<TextBlock Margin="0,16,0,0"
Text="{Binding PackageInfo}" />
<TextBlock Margin="0,8,0,0"
Text="{Binding Status}" />
</StackPanel>
</TabItem>
</TabControl>

TabControl 是页签容器,TabItem 是一页。这里先只放一页,后面每章加一页。

5. 第二步:写最小代码

打开 CommunityToolkitDemo.csproj,确认有这两个包:

1
2
3
4
<ItemGroup>
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
</ItemGroup>

先检查项目是不是旧式包管理

[ObservableProperty] 不是普通代码,它要靠“源生成器”在编译时帮你生成 Name 属性。旧式的 packages.config 项目不会正确加载这个源生成器,表现出来就是:程序能启动,但文本框是空的,下面的 {Binding Name} 也不显示,而且不一定报错。

请打开 .csproj 检查两件事:

  1. 项目里要有上面的 <PackageReference ... />,不要只引用 packages\...\CommunityToolkit.Mvvm.dll。
  2. 项目根目录不要再保留 packages.config;如果 Visual Studio 里有“迁移 packages.config 到 PackageReference”,优先用它迁移。

另外,.NET Framework 4.8 项目默认可能使用较旧的 C# 版本,请在 .csproj 的第一个 <PropertyGroup> 里加上:

1
<LangVersion>8.0</LangVersion>

改完后关闭正在运行的程序,执行“清理解决方案”,再“重新生成解决方案”。如果看到 MVVMTK0008,就是 C# 语言版本还不够,按这里改成 8.0 即可。

新建 ViewModels/PreparationViewModel.cs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using CommunityToolkit.Mvvm.ComponentModel;

namespace CommunityToolkitDemo.ViewModels
{
public class PreparationViewModel : ObservableObject
{
private string _status = "CommunityToolkit.Mvvm 已就绪";

// 表达式体属性:等价于 get { return "..."; }
public string PackageInfo => "CommunityToolkit.Mvvm 8.2.1";

public string Status
{
get => _status; // 等价于 get { return _status; }
set => SetProperty(ref _status, value); // 等价于 set { ... }
}
}
}

这里先不用特性,只用 ObservableObject 和 SetProperty,让你看清最基本的通知写法。

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

这一章先用最简单的办法,在 MainWindow.xaml.cs 的构造函数里直接创建 ViewModel:

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

并在文件顶部加上:

1
using CommunityToolkitDemo.ViewModels;

现在 DataContext 是 PreparationViewModel,所以 XAML 里的 {Binding PackageInfo} 和 {Binding Status} 会去这个对象里找属性。

第 3 章会把这里改成从 IoC 容器获取 MainViewModel。现在先不要急着上容器,先把“界面找数据”这件事看懂。

7. 关键代码逐段看

先看 PreparationViewModel : ObservableObject。

ObservableObject 实现了 INotifyPropertyChanged。它的作用是:属性值变化后,能通知界面重新读取。

再看:

1
set => SetProperty(ref _status, value);

SetProperty 会做三件事:

  1. 比较新值和旧值是否相同。
  2. 不同就赋值。
  3. 触发 PropertyChanged,告诉界面刷新。

最后看 PackageInfo。public string PackageInfo => "..."; 是表达式体属性,等价于只写了一个 get 的只读属性。它没有 set,所以不需要通知;界面每次读取时都会得到右边那句话。

get => _status; 和 set => SetProperty(...); 也是同一种简写:花括号里只有一句时,可以把 { return ...; } 或 { ...; } 写成 => ...。你现在不习惯时,完全可以在脑子里把它还原成传统的 get { }、set { } 写法。

8. 运行后应该看到什么

启动窗口,点击“1 基本使用”页签,应该看到:

  • 标题:CommunityToolkit.Mvvm 基本使用
  • 包信息:CommunityToolkit.Mvvm 8.2.1
  • 状态:CommunityToolkit.Mvvm 已就绪

如果界面空白,先检查 DataContext 是否设置成功。

9. 对应截图或配图

下面是课件中关于 CommunityToolkit.Mvvm 的介绍截图:

课件截图:CommunityToolkit.Mvvm 介绍

先看截图中间的包名和安装方式,再看下方的支持框架说明。课件里提到“UI Framework 不可知”时,不要理解成“不能做 WPF”;本示例实际使用的就是 WPF 项目。

10. 跟做检查点

  • 项目是 WPF 项目,不是控制台项目。
  • .csproj 里有 CommunityToolkit.Mvvm。
  • PreparationViewModel 继承了 ObservableObject。
  • MainWindow 的 DataContext 是 PreparationViewModel。
  • 页面上能看到包信息和状态文字。

11. 常见错误

现象 常见原因 解决
界面空白 没有设置 DataContext 在构造函数里设置 DataContext
找不到 ObservableObject 没有安装包或缺少 using 检查 NuGet 包和命名空间
绑定属性不显示 XAML 属性名拼错 对照 ViewModel 的属性名逐字检查
一运行就报 XAML 错误 TabControl 标签没有闭合 检查每个 TabItem 的结束标签

12. 小练习

把 Status 的初始文字改成 "准备开始学习 CommunityToolkit",再运行一次。你只改一个字符串,观察界面是否跟着变化。

13. 小结与迁移

这一章的主线是:

WPF 项目负责界面,ObservableObject 负责让界面知道数据变了。

以后你新建任何 MVVM 页面,都可以先做一个最小的 ViewModel,再考虑命令、服务和验证。


2. CommunityToolkit中的可观察对象与通知属性

1. 本节目标

用 [ObservableProperty] 让一个字段自动变成可通知的属性,并在文本框中输入文字时,让界面实时更新。

做完后应该看到:在文本框里把“小明”改成“小红”,下面的文字也跟着变成“小红”。

2. 一句话原理

[ObservableProperty] 是源生成器特性。你在字段上贴标签,编译器在后台帮你生成一个带 get、set 和 PropertyChanged 通知的公开属性。

本章真正要学的思维:状态变化要能被界面看见。

  • 字段是类内部的存储,属性是外部观察这个状态的窗口。
  • 属性变化后发出 PropertyChanged,WPF 才知道要重新读取绑定值。
  • [ObservableProperty] 只是帮你少写重复代码,它没有改变“状态变化 → 通知 → 界面刷新”这条链路。
  • 判断方法:这个值在运行中会变吗?会变,就需要通知;只是固定常量,就不需要。
  • 不要把所有东西都做成可通知属性。先分清“状态”和“常量”,再决定用哪种写法。

3. 要改哪里

顺序 文件 位置 要做什么
1 ViewModels/ObservableDemoViewModel.cs 新建类 写 [ObservableProperty] 字段
2 MainWindow.xaml 第二个 TabItem 放 TextBox 和 TextBlock
3 MainWindow.xaml.cs 构造函数 临时把 DataContext 换成这个 ViewModel

4. 第一步:写最小界面

在 TabControl 里增加第二个页签:

1
2
3
4
5
6
7
8
9
10
11
<TabItem Header="2 可观察对象">
<StackPanel Margin="24">
<TextBlock Text="ObservableObject 与通知属性"
FontSize="26" FontWeight="Bold" />
<TextBlock Margin="0,20,0,0" Text="姓名:" />
<TextBox Width="260" HorizontalAlignment="Left"
Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Margin="0,16,0,0"
Text="{Binding Name, StringFormat=当前姓名:{0}}" />
</StackPanel>
</TabItem>

UpdateSourceTrigger=PropertyChanged 表示每输入一个字符就更新 ViewModel,不等失去焦点。

5. 第二步:写最小代码

新建 ViewModels/ObservableDemoViewModel.cs:

1
2
3
4
5
6
7
8
9
10
using CommunityToolkit.Mvvm.ComponentModel;

namespace CommunityToolkitDemo.ViewModels
{
public partial class ObservableDemoViewModel : ObservableObject
{
[ObservableProperty]
private string _name = "小明";
}
}

注意两个点:

  1. 类必须写 partial。因为 [ObservableProperty] 会在编译时生成另一半类代码,partial 允许两半合并;详细原因见本节第 7 部分。
  2. 字段名 _name 会生成公开属性 Name。

完整代码里还会看到一行 public string Greeting => $"你好,{Name}";。它的读法和后面的 FullName 一样:=> 左边是属性名,所以这是只读计算属性;每次读取 Greeting 时,都会用当前的 Name 重新拼出问候语。

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

这一章先把 MainWindow.xaml.cs 的 DataContext 临时改成:

1
DataContext = new ObservableDemoViewModel();

运行后,XAML 里的 {Binding Name} 就能找到这个属性。

后面第 3 章会把 DataContext 换成 MainViewModel。到那时,绑定路径会变成 ObservableDemo.Name,因为 ViewModel 被装进了另一个 ViewModel 里。现在先用最简单的一层。

7. 关键代码逐段看

先看 [ObservableProperty]。

它不是普通的 C# 注释,而是告诉源生成器:“请把这个字段变成可通知属性。”

再看 private string _name = "小明";。

你写的是私有字段,生成出来的是公开属性 Name。所以 XAML 绑定的是 Name,不是 _name。

最后看 public partial class。

这里要重点理解“为什么必须写 partial”。

partial 的意思是“这个类可以分成几部分来写”。平时一个类写在一个文件里;加了 partial 后,编译器允许你在另一个文件里再写一次同名类,最后把它们合并成一个类。

[ObservableProperty] 的工作过程可以想成:

  1. 你在 ObservableDemoViewModel.cs 里写“左半边”:字段 _name 和特性 [ObservableProperty]。
  2. 编译时,源生成器自动生成“右半边”:公开属性 Name、get/set 和属性变化通知。
  3. 编译器把“左半边”和“右半边”拼成一个完整的 ObservableDemoViewModel。

简化示意如下(不是生成器逐字输出的代码):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// 你写的部分
public partial class ObservableDemoViewModel : ObservableObject
{
[ObservableProperty]
private string _name = "小明";
}

// 生成器在编译时补上的部分(示意)
public partial class ObservableDemoViewModel
{
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
_name = value;
OnPropertyChanged(nameof(Name));
}
}
}
}

如果类不写 partial,编译器就不允许把生成器补出来的 Name 属性并进这个类,源生成器也就无法完成工作。所以你看到的不是“框架要求你多写一个单词”,而是“这个类要和自动生成的代码拼在一起,必须先允许拆分”。

可以用一个生活化的比喻:partial 就像告诉编译器“这个类可以由两个人分别写两半,最后装订成一本完整的书”。[ObservableProperty] 负责写另一半,你负责写字段这一半;没有 partial,编译器就不允许“装订”。

还要注意:partial 只影响编译时怎么组织代码,不会多创建一个对象,也不会改变运行结果。它不是继承,也不是接口。

以后遇到类似“特性 + 源生成器”的写法,可以固定问自己三个问题:

  1. 这个特性会不会在编译时生成代码?
  2. 生成的代码要放到哪个类里?
  3. 那个类有没有用 partial 给生成器留位置?

想清楚这三点,就不容易漏写 partial 了。

8. 运行后应该看到什么

打开第二个页签,文本框里默认是“小明”。把文字改成“小红”,下面的“当前姓名”会立即跟着变。

如果只在文本框失去焦点后才变化,检查 UpdateSourceTrigger 是否写成了 PropertyChanged。

9. 对应截图或配图

下面是课件中“常规对象”和“扩展对象”的截图:

课件截图:常规对象与扩展对象

先看上半部分的 ObservableObject、RelayCommand、Messenger,再看下半部分的特性、AsyncRelayCommand 和消息接收对象。后面几章会按这个顺序逐个展开。

10. 跟做检查点

  • ViewModel 类有 partial。
  • 字段上有 [ObservableProperty]。
  • XAML 绑定的是生成的 Name,不是 _name。
  • 输入文字后界面立即变化。

11. 常见错误

现象 常见原因 解决
编译报找不到 Name 类没有写 partial,生成器无法把代码合并进来 改成 public partial class
绑定没有反应 绑定了 _name XAML 改成 Name
输入后不更新 没有设置 UpdateSourceTrigger 加上 PropertyChanged
程序能运行,但文本框空白、下面也不显示 项目用了旧式 packages.config,源生成器没有运行 改成 PackageReference,删除 packages.config,再重新生成
编译报 MVVMTK0008 项目的 C# 语言版本低于 8.0 在 .csproj 里加 <LangVersion>8.0</LangVersion>
改了代码但界面还是旧样子 正在运行旧程序,或编译没有成功 停止调试,清理解决方案,再重新生成

12. 小练习

给 ViewModel 再加一个字段:

1
2
[ObservableProperty]
private int _age = 18;

然后在 XAML 里显示 {Binding Age}。观察 _age 如何自动变成 Age。

13. 小结与迁移

这一章只要记住:

[ObservableProperty] 把“字段 + get/set + 通知”这套重复代码交给了源生成器。

以后写普通通知属性时优先用它;需要自己控制 setter 逻辑时,再手写 SetProperty。


3. CommunityToolkit中的命令对象与IoC使用

1. 本节目标

让按钮通过 [RelayCommand] 调用 ViewModel 方法,并让 ViewModel 通过构造函数拿到一个服务。你会同时看到命令和 IoC 的配合。

做完后点击“通过命令打招呼”,应该看到:

1
你好,小明!这条消息来自 IoC 注入的服务。

2. 一句话原理

按钮不直接调用方法,而是绑定一个命令;命令再调用 ViewModel 方法。ViewModel 不自己创建服务,而是让 IoC 容器把服务从构造函数送进来。

本章真正要学的思维:依赖不要自己造,先声明出来,再集中装配。

  • 命令思维:界面不直接调用方法,而是发出“我要执行这个动作”的意图;ViewModel 决定具体做什么。
  • IoC 思维:构造函数是“需求清单”,注册是“提供能力”,解析是“取装配好的成品”。
  • 判断方法:这个类需要什么?它应该依赖接口还是具体实现?谁负责创建它?
  • 迁移到其他项目:先找“对象在哪里组装”,通常就是启动入口或 App 类;找到组装点,就能看懂整个依赖关系。
  • 不要背 AddSingleton 的顺序,先画依赖箭头:谁需要谁,谁在最上层,谁在底层。

3. 要改哪里

顺序 文件 位置 要做什么
1 Services/IGreetingService.cs 新建接口 定义打招呼服务
2 Services/GreetingService.cs 新建实现 返回问候文字
3 ViewModels/CommandIocViewModel.cs 新建类 写命令和构造函数注入
4 App.xaml.cs App 构造函数 注册服务和 ViewModel
5 ViewModels/MainViewModel.cs 新建类 把各页 ViewModel 装起来
6 MainWindow.xaml.cs 构造函数 从容器取 MainViewModel

4. 第一步:写最小界面

增加第三个页签:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<TabItem Header="3 命令与 IoC">
<StackPanel Margin="24">
<TextBlock Text="RelayCommand 与 IoC"
FontSize="26" FontWeight="Bold" />
<TextBlock Margin="0,20,0,0" Text="姓名:" />
<TextBox Width="260" HorizontalAlignment="Left"
Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />
<Button Margin="0,16,0,0" Width="160" HorizontalAlignment="Left"
Content="通过命令打招呼"
Command="{Binding SayHelloCommand}" />
<TextBlock Margin="0,20,0,0"
Text="{Binding Message}"
TextWrapping="Wrap" />
</StackPanel>
</TabItem>

此时如果 DataContext 还是上一章的 ObservableDemoViewModel,绑定会找不到 SayHelloCommand。下一步会把它换成带命令的 ViewModel。

5. 第二步:写最小代码

先新建 Services/IGreetingService.cs:

1
2
3
4
5
6
7
namespace CommunityToolkitDemo.Services
{
public interface IGreetingService
{
string GetGreeting(string name);
}
}

再新建 Services/GreetingService.cs:

1
2
3
4
5
6
7
8
9
10
namespace CommunityToolkitDemo.Services
{
public class GreetingService : IGreetingService
{
public string GetGreeting(string name)
{
return $"你好,{name}!这条消息来自 IoC 注入的服务。";
}
}
}

然后新建 ViewModels/CommandIocViewModel.cs:

这里的 CommandIocViewModel 也必须写 partial。因为 [ObservableProperty] 要往这个类里生成 Name、Message 属性,[RelayCommand] 要往这个类里生成 SayHelloCommand 属性。源生成器生成的代码需要和你的类合并,所以类必须先允许拆分。

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 CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkitDemo.Services;

namespace CommunityToolkitDemo.ViewModels
{
public partial class CommandIocViewModel : ObservableObject
{
private readonly IGreetingService _greetingService;

[ObservableProperty]
private string _name = "小明";

[ObservableProperty]
private string _message = "点击按钮,通过命令调用服务。";

public CommandIocViewModel(IGreetingService greetingService)
{
_greetingService = greetingService;
}

[RelayCommand]
private void SayHello()
{
Message = _greetingService.GetGreeting(Name);
}
}
}

**为什么 Message ** 会报 CS0103?

[RelayCommand] 只负责把 SayHello() 变成可以在 XAML 里绑定的 SayHelloCommand,它不会顺便生成 Message 或 Name。

这段方法里出现的三个名字,分别来自同一个类里的三处代码:

方法里的名字 来自哪里 谁负责生成或赋值
Message [ObservableProperty] private string _message = "..."; 源生成器根据 _message 生成公开属性 Message
Name [ObservableProperty] private string _name = "小明"; 源生成器根据 _name 生成公开属性 Name
_greetingService private readonly IGreetingService _greetingService; 和构造函数 构造函数注入时赋值

所以如果你只把 SayHello() 方法复制进去,而没有把上面的字段、构造函数一起放进 CommandIocViewModel,编译器就会说“当前上下文中不存在名称 Message”。

检查顺序:

  1. SayHello() 是不是写在 CommandIocViewModel 这个类里面,而不是写在别的 ViewModel 里。
  2. _name、_message、_greetingService 是不是都写在这个类的“类里面、方法外面”。
  3. 类名前面是不是有 partial,并且继承了 ObservableObject。
  4. 文件有没有保存,保存后有没有重新生成。

记住一句话:[RelayCommand] 管“命令”,[ObservableProperty] 管“属性”,构造函数管“服务”。三者要放在同一个 ViewModel 类里配合工作。

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

这一章开始把各页 ViewModel 装进 MainViewModel。新建 ViewModels/MainViewModel.cs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
namespace CommunityToolkitDemo.ViewModels
{
public class MainViewModel
{
public PreparationViewModel Preparation { get; }
public ObservableDemoViewModel ObservableDemo { get; }
public CommandIocViewModel CommandIoc { get; }

public MainViewModel(
PreparationViewModel preparation,
ObservableDemoViewModel observableDemo,
CommandIocViewModel commandIoc)
{
Preparation = preparation;
ObservableDemo = observableDemo;
CommandIoc = commandIoc;
}
}
}

在 App.xaml.cs 里注册:

先确认包已经安装

ServiceCollection 不是 CommunityToolkit.Mvvm 里的类型,它来自:

1
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />

如果看到 CS0246:未能找到类型或命名空间名“ServiceCollection”,先检查项目里有没有这个包,再检查文件顶部有没有:

1
using Microsoft.Extensions.DependencyInjection;

这两个条件缺一个,编译器都不认识 ServiceCollection。

版本不必和笔记完全一样。你项目里安装 11.0.0 也可以,只要 NuGet 能正常还原;笔记里的 7.0.0 只是示例。

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
using CommunityToolkitDemo.Services;
using CommunityToolkitDemo.ViewModels;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Windows;

namespace CommunityToolkitDemo
{
public partial class App : Application
{
public static IServiceProvider Services { get; private set; } = null!;

public App()
{
var services = new ServiceCollection();
services.AddSingleton<IGreetingService, GreetingService>();
services.AddSingleton<PreparationViewModel>();
services.AddSingleton<ObservableDemoViewModel>();
services.AddSingleton<CommandIocViewModel>();
services.AddSingleton<MainViewModel>();

Services = services.BuildServiceProvider();
}
}
}

这段代码可以理解成“先列一张创建对象的清单,再按清单造一个对象工厂”:

代码 通俗理解 为什么需要
var services = new ServiceCollection(); 新建一张空的“服务登记表” 先把“谁负责创建什么对象”记下来
services.AddSingleton<IGreetingService, GreetingService>(); 登记:以后有人要 IGreetingService,就给他一个 GreetingService 让 ViewModel 不直接依赖具体实现
services.AddSingleton<PreparationViewModel>(); 登记:PreparationViewModel 也交给容器创建 后面 MainViewModel 需要它
services.AddSingleton<ObservableDemoViewModel>(); 登记:ObservableDemoViewModel 交给容器创建 后面 MainViewModel 需要它
services.AddSingleton<CommandIocViewModel>(); 登记:CommandIocViewModel 交给容器创建 它自己还需要 IGreetingService,容器会继续帮它找
services.AddSingleton<MainViewModel>(); 登记:主 ViewModel 也交给容器创建 它需要前面三个页面 ViewModel
Services = services.BuildServiceProvider(); 把登记表变成真正的“对象工厂” 之后才能用 GetRequiredService<T>() 取对象

这里最关键的是理解“依赖链”:

1
2
3
4
5
6
MainViewModel
├── PreparationViewModel
├── ObservableDemoViewModel
└── CommandIocViewModel
└── IGreetingService
└── GreetingService

MainViewModel 的构造函数需要三个页面 ViewModel,所以这三个都要先登记;CommandIocViewModel 的构造函数又需要 IGreetingService,所以服务也要登记。容器会顺着构造函数一层一层把对象创建出来。

AddSingleton 的意思是“整个程序运行期间只创建一个实例,大家共用”。例如 GreetingService 只创建一次;如果你希望每次取都创建新对象,可以改用 AddTransient。

注册顺序通常不重要,重要的是“需要用到的类型都登记了”。但 BuildServiceProvider() 一般只在启动时调用一次,不要每次取对象都重新创建容器。

最后把 MainWindow.xaml.cs 改成:

1
2
3
4
5
6
7
8
9
using CommunityToolkitDemo.ViewModels;
using Microsoft.Extensions.DependencyInjection;
using System.Windows;

public MainWindow()
{
InitializeComponent();
DataContext = App.Services.GetRequiredService<MainViewModel>();
}

这一行可以拆成三段来读:

1
2
App.Services
.GetRequiredService<MainViewModel>();
  1. App.Services:拿到 App 里保存的那个“对象工厂”。它在 App 构造函数里通过 BuildServiceProvider() 建好。
  2. GetRequiredService<MainViewModel>():向工厂要一个 MainViewModel。工厂会看它的构造函数需要什么,再继续创建它需要的对象。
  3. DataContext = ...:把创建好的 MainViewModel 交给窗口,窗口里的 {Binding ...} 就从这个对象开始找属性。

这里其实有两个阶段:

阶段 代码 做什么
登记 services.AddSingleton<...>(); 告诉容器“这种对象应该怎么创建”
解析 GetRequiredService<MainViewModel>() 让容器按照登记表,把对象真正创建出来

可以把它想成一家餐厅:

  • ServiceCollection 是菜单,先写清楚“有哪些菜、用什么材料”。
  • BuildServiceProvider() 是把菜单交给厨房,开张营业。
  • GetRequiredService<MainViewModel>() 是点菜:我要一份 MainViewModel,厨房负责把它需要的配料一起准备好。

为什么不能直接写 new MainViewModel()?因为 MainViewModel 的构造函数需要三个页面 ViewModel,而 CommandIocViewModel 又需要 IGreetingService。如果手写 new,就要自己一层一层把依赖都创建出来;用了容器,只需要登记一次,容器会顺着构造函数自动装配。

手写 new 大致会变成这样:

1
2
3
4
5
6
var greetingService = new GreetingService();
var commandIoc = new CommandIocViewModel(greetingService);
var preparation = new PreparationViewModel();
var observable = new ObservableDemoViewModel();
var main = new MainViewModel(preparation, observable, commandIoc);
DataContext = main;

这里只要 CommandIocViewModel 的构造函数以后多一个参数,这段代码就要跟着改;依赖越多,手工组装的链条越长。容器的价值就是把这个“组装过程”集中管理起来。

GetRequiredService 里的 Required 表示“必须有”。如果某个类型忘记登记,它会直接报错,方便你尽早发现问题;如果使用 GetService,找不到时可能只得到 null,反而不容易排查。

所以看到 DataContext = App.Services.GetRequiredService<MainViewModel>(); 时,可以按这个顺序想:

  1. 窗口需要一个 MainViewModel 作为数据源。
  2. 不要自己 new,交给已经登记好的容器创建。
  3. 容器会自动把 PreparationViewModel、ObservableDemoViewModel、CommandIocViewModel 和 IGreetingService 一层层装配好。
  4. 最后把装配好的 MainViewModel 赋给 DataContext。

自己写注册代码时,可以固定按这 5 步想:

  1. 先找最上层是谁:MainWindow 需要 MainViewModel。
  2. 再看 MainViewModel 的构造函数需要什么。
  3. 继续看它依赖的 ViewModel 又需要什么。
  4. 把所有依赖登记到 ServiceCollection。
  5. 最后只在 MainWindow 里解析最上层的 MainViewModel。

这时 XAML 的绑定路径要改成:

1
2
3
<TextBox Text="{Binding CommandIoc.Name, UpdateSourceTrigger=PropertyChanged}" />
<Button Command="{Binding CommandIoc.SayHelloCommand}" />
<TextBlock Text="{Binding CommandIoc.Message}" />

同时把前两页的绑定也改成新的层级:

1
2
3
4
5
6
<!-- 第 1 页 -->
Text="{Binding Preparation.PackageInfo}"
Text="{Binding Preparation.Status}"

<!-- 第 2 页 -->
Text="{Binding ObservableDemo.Name, UpdateSourceTrigger=PropertyChanged}"

原因是 DataContext 已经从某一个具体 ViewModel 变成了 MainViewModel,而 MainViewModel 里才有 Preparation、ObservableDemo 和 CommandIoc 这些属性。

第 3 页没反应时先检查这里

如果按钮点了没反应,先打开 MainWindow.xaml.cs,看 DataContext 是不是还停在:

1
DataContext = new ObservableDemoViewModel();

如果是,窗口的数据源里没有 CommandIoc,绑定 CommandIoc.SayHelloCommand 自然找不到。要改成:

1
DataContext = App.Services.GetRequiredService<MainViewModel>();

6.1 这一节真正要学的思维

不要只记住这几行代码,而要记住它们背后的四个想法。

**想法一:对象不要到处自己 ****new**

以前可能是“谁需要什么,谁就自己创建”:

1
2
var service = new GreetingService();
var viewModel = new CommandIocViewModel(service);

现在改成“先登记,再让容器装配”:

1
2
services.AddSingleton<IGreetingService, GreetingService>();
services.AddSingleton<CommandIocViewModel>();

这不是为了少写几个字,而是为了把“创建对象”和“使用对象”分开。以后换实现、加日志、加数据库、做测试,只需要改登记处,不用把所有 new 的地方翻一遍。

想法二:构造函数就是“需求清单”

看到这个构造函数:

1
public CommandIocViewModel(IGreetingService greetingService)

不要只把它当成普通参数,而要读成:

谁创建我,谁就要先给我一个 IGreetingService。

所以容器创建 CommandIocViewModel 时,会先去找 IGreetingService 的登记,再创建它需要的 GreetingService。构造函数写得越清楚,依赖关系就越清楚。

想法三:面向接口,不面向具体实现

CommandIocViewModel 需要的是:

1
IGreetingService

而不是直接写死:

1
GreetingService

这样以后可以把 GreetingService 换成“正式服务”“测试服务”“模拟服务”,ViewModel 的代码不用改,只需要改注册:

1
services.AddSingleton<IGreetingService, GreetingService>();

这就是“依赖倒置”的入门版:高层代码依赖抽象,不依赖具体细节。

想法四:只在最上层解析一次

App 负责登记,MainWindow 只负责拿最上层的 MainViewModel:

1
DataContext = App.Services.GetRequiredService<MainViewModel>();

不要在 MainWindow 里写:

1
2
var service = App.Services.GetRequiredService<IGreetingService>();
var command = App.Services.GetRequiredService<CommandIocViewModel>();

因为 MainViewModel 已经把这些依赖装好了。最上层只拿“总装好的对象”,内部依赖交给容器处理。

以后遇到新功能,就按这个顺序想

  1. 这个功能需要什么服务?先定义接口。
  2. 谁需要使用这个服务?看它的构造函数。
  3. 这个对象应该注册成 Singleton 还是 Transient?
  4. 在 App 里登记服务和 ViewModel。
  5. 在 MainWindow 只解析最上层的 MainViewModel。
  6. XAML 按照 MainViewModel 的属性层级写绑定路径。

可以记成一句话:

先想“谁需要谁”,再想“谁负责创建”,最后才写代码。

7. 关键代码逐段看

先看 [RelayCommand]。它放在 SayHello 方法上,源生成器会生成一个名为 SayHelloCommand 的属性。XAML 不需要认识方法,只需要绑定命令。

再看构造函数:

1
public CommandIocViewModel(IGreetingService greetingService)

这句话表示:“创建我时,请把一个 IGreetingService 递进来。”ViewModel 不再自己 new GreetingService()。

最后看注册:

1
2
services.AddSingleton<IGreetingService, GreetingService>();
services.AddSingleton<CommandIocViewModel>();

第一行告诉容器接口对应哪个实现;第二行告诉容器 ViewModel 也可以由它创建。容器看到 CommandIocViewModel 的构造函数需要一个服务,就会先创建服务,再创建 ViewModel。

8. 运行后应该看到什么

打开第三个页签,点击按钮,消息区域显示:

1
你好,小明!这条消息来自 IoC 注入的服务。

在文本框中改名字,再点击按钮,问候语里的名字也会变化。

9. 对应截图或配图

命令与 IoC 的调用链

先看最上面一条链:XAML 按钮 → RelayCommand → ViewModel 方法 → 注入的服务。再看左下角的注册代码,理解“谁负责创建服务”。

10. 跟做检查点

  • CommandIocViewModel 有 [RelayCommand]。
  • 方法名 SayHello 对应生成属性 SayHelloCommand。
  • 构造函数接收 IGreetingService。
  • App 里注册了接口、实现和 ViewModel。
  • MainWindow 从 App.Services 取 MainViewModel。

11. 常见错误

现象 常见原因 解决
按钮没有反应 XAML 绑定了错误命令名 SayHello 生成的是 SayHelloCommand
报“无法解析 IGreetingService” 没有注册接口 在 App 中注册服务
DataContext 是 null 容器没有创建 MainViewModel 注册 MainViewModel 并调用 GetRequiredService
绑定路径找不到 还在用 Name,但现在多了一层 改成 CommandIoc.Name

12. 小练习

把 GreetingService 的返回文字改成 "欢迎 {name} 学习 CommunityToolkit",再运行。你只改服务,不改按钮和 XAML,体会“界面不关心服务内部怎么实现”。

13. 小结与迁移

这一章的主线是:

命令负责把按钮动作转成方法调用,IoC 负责把服务送到 ViewModel 手里。

以后按钮越来越多时,先问自己:这个动作属于哪个 ViewModel?它需要什么服务?然后把服务注册到容器里。


4. CommunityToolkit中的通知属性特性使用

1. 本节目标

用 [NotifyPropertyChangedFor] 解决“一个字段变化,另一个计算属性也要刷新”的问题。

做完后在两个文本框里改姓或名,下面的完整姓名会立即更新。

2. 一句话原理

[ObservableProperty] 只通知自己生成的属性;如果另一个属性依赖它,就要额外告诉通知系统:“这个属性变了,也请通知另一个属性。”

本章真正要学的思维:状态之间会互相影响,变化要沿着依赖关系传播。

  • FirstName 和 LastName 是原始状态,FullName 是由它们算出来的结果。
  • [ObservableProperty] 只负责通知自己;[NotifyPropertyChangedFor(nameof(FullName))] 负责告诉界面:“依赖它的 FullName 也变了。”
  • 判断方法:改一个值以后,界面上还有哪些显示会受影响?把这些依赖列出来,再决定通知谁。
  • 能算出来的值,尽量不要重复存成字段。重复存两份状态,就多一份“忘记同步”的风险。
  • 迁移到其他场景:总价、库存、全名、格式化地址、状态文字,都是“原始状态 + 计算属性”的组合。

3. 要改哪里

顺序 文件 位置 要做什么
1 ViewModels/PropertyAttributesViewModel.cs 新建类 写两个带通知特性的字段
2 MainWindow.xaml 第四个 TabItem 放两个 TextBox 和一个 FullName
3 ViewModels/MainViewModel.cs 构造函数 注入这个 ViewModel
4 App.xaml.cs 注册区 注册这个 ViewModel

4. 第一步:写最小界面

增加第四个页签:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<TabItem Header="4 属性特性">
<StackPanel Margin="24">
<TextBlock Text="通知属性特性"
FontSize="26" FontWeight="Bold" />
<TextBlock Margin="0,20,0,0" Text="姓:" />
<TextBox Width="260" HorizontalAlignment="Left"
Text="{Binding FirstName, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Margin="0,12,0,0" Text="名:" />
<TextBox Width="260" HorizontalAlignment="Left"
Text="{Binding LastName, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Margin="0,20,0,0"
Text="{Binding FullName, StringFormat=完整姓名:{0}}" />
</StackPanel>
</TabItem>

5. 第二步:写最小代码

新建 ViewModels/PropertyAttributesViewModel.cs:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using CommunityToolkit.Mvvm.ComponentModel;

namespace CommunityToolkitDemo.ViewModels
{
public partial class PropertyAttributesViewModel : ObservableObject
{
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(FullName))]
private string _firstName = "张";

[ObservableProperty]
[NotifyPropertyChangedFor(nameof(FullName))]
private string _lastName = "三";

// 表达式体属性:每次读取时,把 FirstName 和 LastName 拼起来
public string FullName => $"{FirstName}{LastName}";
}
}

FullName 没有 set,它不是输入框直接修改的属性;它是由 FirstName 和 LastName 算出来的。

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

在 MainViewModel 里增加属性,并通过构造函数注入:

1
2
3
4
5
6
7
8
9
10
11
12
13
public PropertyAttributesViewModel PropertyAttributes { get; }

public MainViewModel(
PreparationViewModel preparation,
ObservableDemoViewModel observableDemo,
CommandIocViewModel commandIoc,
PropertyAttributesViewModel propertyAttributes)
{
Preparation = preparation;
ObservableDemo = observableDemo;
CommandIoc = commandIoc;
PropertyAttributes = propertyAttributes;
}

在 App.xaml.cs 中注册:

1
services.AddSingleton<PropertyAttributesViewModel>();

XAML 的绑定路径改成:

1
2
3
Text="{Binding PropertyAttributes.FirstName, UpdateSourceTrigger=PropertyChanged}"
Text="{Binding PropertyAttributes.LastName, UpdateSourceTrigger=PropertyChanged}"
Text="{Binding PropertyAttributes.FullName, StringFormat=完整姓名:{0}}"

7. 关键代码逐段看

先看:

1
[NotifyPropertyChangedFor(nameof(FullName))]

它的意思是:“当这个字段对应的属性变化时,也通知 FullName 变了。”

如果没有这句话,修改 FirstName 只会通知 FirstName,界面可能不知道要重新读取 FullName。

再看 public string FullName => $"{FirstName}{LastName}";。

这里的 => 不是 Lambda,因为左边是属性名 FullName。它是表达式体属性,等价于:

1
2
3
4
public string FullName
{
get { return $"{FirstName}{LastName}"; }
}

它每次被读取时都会重新计算,所以只要通知到位,界面就能拿到最新的完整姓名。

$"..." 是字符串插值:字符串前面的 $ 表示“里面的 {FirstName} 会被替换成属性的值”。如果你把 $ 去掉,界面就会原样显示 {FirstName},而不是真实姓名。

最后看 nameof(FullName)。它比手写字符串 "FullName" 更安全:以后改属性名,编译器会提醒你。

8. 运行后应该看到什么

打开第四个页签,默认显示:

1
完整姓名:张三

把“张”改成“李”,或把“三”改成“四”,完整姓名会立即更新。

9. 对应截图或配图

通知属性特性的生成过程

先看左边“你写的字段”,再看中间“源生成器生成”,最后看右边“界面绑定”。这张图对应本章最重要的三行代码。

10. 跟做检查点

  • 两个字段都有 [ObservableProperty]。
  • 两个字段都有 [NotifyPropertyChangedFor(nameof(FullName))]。
  • FullName 是只读计算属性。
  • XAML 绑定的是 FirstName、LastName 和 FullName。

11. 常见错误

现象 常见原因 解决
改姓后 FullName 不更新 忘记 NotifyPropertyChangedFor 给两个字段都加上
编译报 nameof 里找不到 属性名拼错 检查 FullName 大小写
界面直接显示空白 绑定了私有字段 绑定生成的公开属性
只更新一个字段 只给一个字段加了通知 两个字段都要加

12. 小练习

增加一个只读属性:

1
public string DisplayName => $"姓名:{FullName}";

然后用 [NotifyPropertyChangedFor(nameof(DisplayName))] 让两个字段变化时也通知它。

13. 小结与迁移

这一章的主线是:

[ObservableProperty] 通知自己,[NotifyPropertyChangedFor] 通知依赖它的其他属性。

以后遇到“完整姓名”“总价”“格式化文字”这类计算属性,就要想到这条规则。


5. CommunityToolkit中的命令与验证特性使用

1. 本节目标

让 ObservableValidator 检查输入,并让命令根据验证结果自动禁用或启用按钮。

做完后:

  • 姓名合法时,“提交”按钮可用。
  • 姓名清空或少于两个字符时,按钮变灰,并显示错误文字。

2. 一句话原理

验证特性负责判断输入是否合法,HasErrors 保存结果;命令的 CanExecute 读取这个结果,决定按钮能不能点。

本章真正要学的思维:规则先判断,状态再记录,界面最后根据状态变化。

  • 输入值先经过验证规则,得到“合法 / 不合法”的结果。
  • HasErrors 保存这个结果,错误文字告诉用户哪里不对。
  • CanExecute 读取验证状态,决定按钮是否可用。
  • 判断方法:什么算合法?错误信息给谁看?这个动作在什么条件下才能执行?
  • 迁移到其他场景:登录、保存设置、提交订单、导入文件,都是“规则 → 状态 → 按钮”的同一套逻辑。
  • 不要把验证写散在按钮点击事件里。规则集中在 ViewModel,界面只负责显示结果。

3. 要改哪里

顺序 文件 位置 要做什么
1 ViewModels/ValidationViewModel.cs 新建类 继承 ObservableValidator,加验证特性
2 MainWindow.xaml 第五个 TabItem 输入框、错误提示和提交按钮
3 ViewModels/MainViewModel.cs 构造函数 注入验证 ViewModel
4 App.xaml.cs 注册区 注册验证 ViewModel

4. 第一步:写最小界面

增加第五个页签:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<TabItem Header="5 命令与验证">
<StackPanel Margin="24">
<TextBlock Text="命令与数据验证"
FontSize="26" FontWeight="Bold" />
<TextBlock Margin="0,20,0,0" Text="姓名(至少两个字符):" />
<TextBox Width="300" HorizontalAlignment="Left"
Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Margin="0,8,0,0" Foreground="#B33A3A"
Text="{Binding ErrorMessage}"
TextWrapping="Wrap" />
<Button Margin="0,16,0,0" Width="160" HorizontalAlignment="Left"
Content="提交"
Command="{Binding SubmitCommand}" />
<TextBlock Margin="0,20,0,0"
Text="{Binding Status}"
TextWrapping="Wrap" />
</StackPanel>
</TabItem>

5. 第二步:写最小代码

新建 ViewModels/ValidationViewModel.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 CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace CommunityToolkitDemo.ViewModels
{
public partial class ValidationViewModel : ObservableValidator
{
[ObservableProperty]
[NotifyDataErrorInfo]
[NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
[Required(ErrorMessage = "姓名不能为空")]
[MinLength(2, ErrorMessage = "姓名至少两个字符")]
private string _name = "小明";

[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
private bool _isBusy;

[ObservableProperty]
private string _status = "等待提交";

// 表达式体属性:把所有验证错误拼成一段文字
public string ErrorMessage =>
string.Join(";",
GetErrors().Select(error => error.ErrorMessage));

public ValidationViewModel()
{
// Lambda:两个参数都不使用,事件发生时通知 ErrorMessage
ErrorsChanged += (_, _) => OnPropertyChanged(nameof(ErrorMessage));
}

private bool CanSubmit()
{
return !IsBusy && !HasErrors && !string.IsNullOrWhiteSpace(Name);
}

[RelayCommand(CanExecute = nameof(CanSubmit))]
private void Submit()
{
Status = $"提交成功:{Name}";
}
}
}

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

在 MainViewModel 里增加:

1
public ValidationViewModel Validation { get; }

构造函数参数增加 ValidationViewModel validation,并赋值。然后在 App.xaml.cs 中注册:

1
services.AddSingleton<ValidationViewModel>();

最后把 XAML 绑定路径改成:

1
2
3
4
Text="{Binding Validation.Name, UpdateSourceTrigger=PropertyChanged}"
Text="{Binding Validation.ErrorMessage}"
Command="{Binding Validation.SubmitCommand}"
Text="{Binding Validation.Status}"

7. 关键代码逐段看

先看 ObservableValidator。它比 ObservableObject 多了一套验证能力,能保存错误并触发 ErrorsChanged。

再看 ErrorMessage 这一行。这里有三个容易混的点:

1
2
public string ErrorMessage =>
string.Join(";", GetErrors().Select(error => error.ErrorMessage));
  1. 最外层的 ErrorMessage => 是表达式体属性,等价于 get { return ...; }。
  2. Select(error => error.ErrorMessage) 里的 error => ... 才是 Lambda。error 是集合中的一个错误对象,右边表示“取出这个对象的 ErrorMessage”。
  3. string.Join(";", ...) 把每个错误文字用中文分号拼成一段。

构造函数里的这一行也是 Lambda:

1
ErrorsChanged += (_, _) => OnPropertyChanged(nameof(ErrorMessage));

(_, _) 表示事件处理方法的两个参数都存在,但这里暂时不用;事件触发时执行右边的 OnPropertyChanged(...)。所以姓名验证结果变化后,界面会重新读取 ErrorMessage。

再看:

1
2
3
[NotifyDataErrorInfo]
[Required(ErrorMessage = "姓名不能为空")]
[MinLength(2, ErrorMessage = "姓名至少两个字符")]

NotifyDataErrorInfo 让生成的属性在变化时执行验证;Required 和 MinLength 是具体的验证规则。

然后看 CanSubmit():

1
return !IsBusy && !HasErrors && !string.IsNullOrWhiteSpace(Name);

这三个条件分别表示:不忙、没有验证错误、姓名不是空白。

最后看 [NotifyCanExecuteChangedFor(nameof(SubmitCommand))]。姓名变化后,它会让命令重新调用 CanSubmit(),按钮状态才会跟着变。

8. 运行后应该看到什么

打开第五个页签:

  1. 默认姓名“小明”合法,按钮可用。
  2. 把姓名清空,按钮变灰,错误文字显示“姓名不能为空”。
  3. 输入“小”,错误文字显示“姓名至少两个字符”。
  4. 输入“小红”,按钮恢复可用,点击后状态显示“提交成功:小红”。

9. 对应截图或配图

命令与验证的状态切换

先看上方“输入框 → 验证属性 → 命令状态”的链条,再看下方红色和绿色两个结果区域。它对应“输入不合法时按钮不可用”的完整逻辑。

10. 跟做检查点

  • 类继承的是 ObservableValidator。
  • 姓名字段有 [NotifyDataErrorInfo]。
  • 验证规则有 [Required] 和 [MinLength]。
  • 命令有 CanExecute = nameof(CanSubmit)。
  • 清空输入时按钮会变灰。

11. 常见错误

现象 常见原因 解决
输入错误但按钮仍可用 没有 NotifyCanExecuteChangedFor 给姓名字段加上
错误文字不更新 没有订阅 ErrorsChanged 在构造函数里通知 ErrorMessage
验证完全不执行 类没有继承 ObservableValidator 改成 ObservableValidator
空字符串没有报错 只写了 MinLength 同时加上 [Required]

12. 小练习

增加一条最大长度验证:

1
[MaxLength(10, ErrorMessage = "姓名不能超过十个字符")]

然后用十一个字符测试按钮状态。

再做一个 Lambda 小练习:把 Select(error => error.ErrorMessage) 改成 Select(error => "[" + error.ErrorMessage + "]"),观察错误文字前后是否多了方括号。你只改 Lambda 右边,不需要改 Select 本身。

13. 小结与迁移

这一章的主线是:

验证特性负责判断,HasErrors 保存结果,CanExecute 决定按钮状态。

以后表单提交、保存设置、登录按钮,都可以沿用这套“验证 + 命令状态”的组合。


6. CommunityToolkit中的异步命令与消息接口

1. 本节目标

用 [RelayCommand] 生成异步命令,让按钮启动一个耗时任务;任务完成后通过 WeakReferenceMessenger 发送消息,再由实现了 IRecipient<T> 的 ViewModel 接收。

做完后点击“开始异步加载”,会先看到“正在加载…”,约一秒后变成“加载完成”,并显示:

1
收到消息:后台任务已经完成

2. 一句话原理

异步命令负责“开始做一件耗时的事”,消息负责“做完后通知关心它的人”。按钮不需要一直等待,接收方也不需要认识发送方。

本章真正要学的思维:耗时任务要管理过程,完成通知要解耦。

  • 异步命令不只管“开始”,还要管“正在执行”“执行完成”“执行失败”这些过程状态。
  • 界面要根据 IsRunning 等状态决定按钮是否可用、是否显示“正在加载…”。
  • Messenger 是发布/订阅:发送方只负责发消息,不需要知道谁在听;接收方只关心自己感兴趣的消息。
  • 判断方法:这个任务要多久?执行期间界面要不要禁用?完成后谁需要知道?失败了怎么显示?
  • 迁移到其他场景:文件导入、HTTP 请求、后台计算、批量处理,都可以沿用“异步命令 + 状态 + 消息”的组合。
  • 不要让页面之间互相直接引用。能通过消息解耦的地方,就不要硬连在一起。

3. 要改哪里

顺序 文件 位置 要做什么
1 Messages/StatusMessage.cs 新建消息类 定义消息内容
2 ViewModels/AsyncMessageViewModel.cs 新建类 写异步命令和接收方法
3 MainWindow.xaml 第六个 TabItem 放异步按钮和状态文字
4 ViewModels/MainViewModel.cs 构造函数 注入异步消息 ViewModel
5 App.xaml.cs 注册区 注册异步消息 ViewModel

4. 第一步:写最小界面

增加第六个页签:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<TabItem Header="6 异步命令与消息">
<StackPanel Margin="24">
<TextBlock Text="异步命令与消息接口"
FontSize="26" FontWeight="Bold" />
<Button Margin="0,20,0,0" Width="180" HorizontalAlignment="Left"
Content="开始异步加载"
Command="{Binding LoadCommand}" />
<TextBlock Margin="0,20,0,0"
Text="{Binding Status, StringFormat=状态:{0}}" />
<TextBlock Margin="0,8,0,0"
Text="{Binding ReceivedMessage, StringFormat=收到消息:{0}}"
TextWrapping="Wrap" />
</StackPanel>
</TabItem>

5. 第二步:写最小代码

先新建消息类型 Messages/StatusMessage.cs:

1
2
3
4
5
6
7
8
9
10
11
using CommunityToolkit.Mvvm.Messaging.Messages;

namespace CommunityToolkitDemo.Messages
{
public class StatusMessage : ValueChangedMessage<string>
{
public StatusMessage(string value) : base(value)
{
}
}
}

再新建 ViewModels/AsyncMessageViewModel.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 CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkitDemo.Messages;
using System.Threading.Tasks;

namespace CommunityToolkitDemo.ViewModels
{
public partial class AsyncMessageViewModel
: ObservableRecipient, IRecipient<StatusMessage>
{
[ObservableProperty]
private string _status = "等待开始";

[ObservableProperty]
private string _receivedMessage = "还没有收到消息";

public AsyncMessageViewModel()
{
IsActive = true;
}

[RelayCommand]
private async Task LoadAsync()
{
Status = "正在加载...";
await Task.Delay(1200);
Status = "加载完成";
WeakReferenceMessenger.Default.Send(
new StatusMessage("后台任务已经完成"));
}

public void Receive(StatusMessage message)
{
ReceivedMessage = message.Value;
}
}
}

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

在 MainViewModel 中增加:

1
public AsyncMessageViewModel AsyncMessage { get; }

构造函数参数增加 AsyncMessageViewModel asyncMessage,并赋值。然后在 App.xaml.cs 中注册:

1
services.AddSingleton<AsyncMessageViewModel>();

最后把 XAML 绑定路径改成:

1
2
3
Command="{Binding AsyncMessage.LoadCommand}"
Text="{Binding AsyncMessage.Status, StringFormat=状态:{0}}"
Text="{Binding AsyncMessage.ReceivedMessage, StringFormat=收到消息:{0}}"

7. 关键代码逐段看

先看:

1
2
[RelayCommand]
private async Task LoadAsync()

方法返回 Task,[RelayCommand] 会生成异步命令 LoadCommand。按钮执行命令时,异步方法开始运行,界面不会被 Task.Delay 卡住。

再看:

1
await Task.Delay(1200);

这里用等待模拟耗时操作。真实项目里可能是读数据库、请求接口或读写文件。

然后看:

1
WeakReferenceMessenger.Default.Send(new StatusMessage("后台任务已经完成"));

发送方只负责发出 StatusMessage,不需要知道谁接收。

最后看 ObservableRecipient 和 IRecipient<StatusMessage>:

1
2
3
4
public void Receive(StatusMessage message)
{
ReceivedMessage = message.Value;
}

IsActive = true 会触发 OnActivated(),把实现了 IRecipient<T> 的接收方法注册到默认 Messenger。消息到达后,Receive 被调用,界面上的 ReceivedMessage 更新。

8. 运行后应该看到什么

打开第六个页签,点击按钮:

  1. 状态先变成“正在加载…”。
  2. 约一秒后变成“加载完成”。
  3. “收到消息”变成“后台任务已经完成”。

自测项目也会输出:

1
2
异步命令状态:加载完成
消息接收结果:后台任务已经完成

9. 对应截图或配图

异步命令与消息的调用链

先看上方“按钮 → AsyncRelayCommand → 后台任务 → 发送消息”的链条,再看下方接收方和 IRecipient<T> 的代码位置。

10. 跟做检查点

  • LoadAsync 返回 Task,不是 async void。
  • 类继承 ObservableRecipient。
  • 类实现 IRecipient<StatusMessage>。
  • 构造函数里设置了 IsActive = true。
  • 发送和接收使用的是同一个 StatusMessage 类型。

11. 常见错误

现象 常见原因 解决
按钮没有异步效果 方法写成了 async void 改成 async Task
消息收不到 没有设置 IsActive = true 在构造函数里激活
消息类型不匹配 发送和接收用了不同消息类 统一使用 StatusMessage
界面卡住 在 UI 线程里用了 .Wait() 或 .Result 使用 await
找不到 WeakReferenceMessenger 缺少 using 加上 CommunityToolkit.Mvvm.Messaging

12. 小练习

把 Task.Delay(1200) 改成 Task.Delay(3000),观察按钮点击后状态先变化、界面仍然可以操作。再增加一条 StatusMessage("第二次任务完成"),看接收方是否更新。

13. 小结与迁移

这一章的主线是:

异步命令负责启动任务,消息负责把“任务完成”通知给关心它的人。

以后做文件导入、接口请求、后台计算时,可以用异步命令;当一个页面完成后需要通知另一个页面,可以用 Messenger,而不是让两个页面互相直接引用。


怎么用这份笔记训练思维

每学完一章,不要只问“代码会不会写”,再按下面 4 个问题过一遍:

  1. 这一章解决的是什么问题?不用这个工具时,手写会遇到什么麻烦?
  2. 这个工具把哪一步变简单了?它没有改变的又是什么?
  3. 这一章的对象之间是什么关系?谁是状态,谁是服务,谁负责通知,谁负责显示?
  4. 换一个场景,我还能怎么用?比如把“打招呼服务”换成“数据库服务”,把“完整姓名”换成“订单总价”。

还可以做一个小练习:每学完一章,用一张纸画三个框:

1
界面(View)  →  状态/动作(ViewModel)  →  服务或数据(Service/Model)

然后在箭头旁边写清楚:

  • 界面绑定了哪些属性?
  • 哪个动作通过命令进入 ViewModel?
  • ViewModel 依赖了哪些服务?
  • 哪个状态变化后,界面需要收到通知?

画得出来,说明你理解了关系;画不出来,再回到代码里找“谁引用谁”。这比死记代码更容易迁移到下一个项目。


运行验证

完整构建:

1
dotnet build .\示例代码\CommunityToolkitDemo\CommunityToolkitDemo.csproj -c Release

本次构建结果:0 个错误,有 net7.0-windows 已停止支持的警告。

ViewModel 自测:

1
dotnet run --project .\示例代码\CommunityToolkitDemo.Tests\CommunityToolkitDemo.Tests.csproj -c Release

实际输出:

1
2
3
4
5
6
7
8
9
10
可观察属性:你好,小红
命令与 IoC:你好,小明!这条消息来自 IoC 注入的服务。
属性特性:李四
验证初始可提交:True
空值可提交:False
空值错误:姓名不能为空
合法值可提交:True
提交结果:提交成功:小明
异步命令状态:加载完成
消息接收结果:后台任务已经完成

最终检查清单

  • 六个章节标题和顺序与目录一致。
  • 每章都有先界面、后代码、再连接的顺序。
  • 每章至少有一张本地图片,并已嵌入正文。
  • 正文代码块都能定位到文件、类和位置。
  • 正文没有直接贴完整项目。
  • 完整代码在最后附录。
  • 构建和 ViewModel 自测结果真实可复现。

附录:完整示例代码

下面是 示例代码/CommunityToolkitDemo 的实际文件。正文为了循序渐进只展示关键片段,附录用于对照和排错。附录里还会出现 => 和 Lambda;如果一时忘了怎么读,回到前面的“读法说明:=> 与 Lambda”对照一下即可。

CommunityToolkitDemo.csproj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net7.0-windows</TargetFramework>
<UseWPF>true</UseWPF>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
</ItemGroup>
</Project>
App.xaml
1
2
3
4
5
6
7
<Application x:Class="CommunityToolkitDemo.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>
App.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
using CommunityToolkitDemo.Services;
using CommunityToolkitDemo.ViewModels;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Windows;

namespace CommunityToolkitDemo
{
public partial class App : Application
{
public static IServiceProvider Services { get; private set; } = null!;

public App()
{
var services = new ServiceCollection();

services.AddSingleton<IGreetingService, GreetingService>();
services.AddSingleton<PreparationViewModel>();
services.AddSingleton<ObservableDemoViewModel>();
services.AddSingleton<CommandIocViewModel>();
services.AddSingleton<PropertyAttributesViewModel>();
services.AddSingleton<ValidationViewModel>();
services.AddSingleton<AsyncMessageViewModel>();
services.AddSingleton<MainViewModel>();

Services = services.BuildServiceProvider();
}
}
}
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
<Window x:Class="CommunityToolkitDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="CommunityToolkit.Mvvm 跟做示例"
Height="720" Width="1000"
FontSize="16"
WindowStartupLocation="CenterScreen">
<Grid Background="#F4F7FB">
<TabControl Margin="20">
<TabItem Header="1 基本使用">
<StackPanel Margin="24">
<TextBlock Text="CommunityToolkit.Mvvm 基本使用"
FontSize="26" FontWeight="Bold" />
<TextBlock Margin="0,16,0,0"
Text="{Binding Preparation.PackageInfo}" />
<TextBlock Margin="0,8,0,0"
Text="{Binding Preparation.Status}" />
</StackPanel>
</TabItem>

<TabItem Header="2 可观察对象">
<StackPanel Margin="24">
<TextBlock Text="ObservableObject 与通知属性"
FontSize="26" FontWeight="Bold" />
<TextBlock Margin="0,20,0,0" Text="姓名:" />
<TextBox Width="260" HorizontalAlignment="Left"
Text="{Binding ObservableDemo.Name, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Margin="0,16,0,0"
Text="{Binding ObservableDemo.Greeting}" />
<TextBlock Margin="0,8,0,0"
Text="{Binding ObservableDemo.Count, StringFormat=计数:{0}}" />
</StackPanel>
</TabItem>

<TabItem Header="3 命令与 IoC">
<StackPanel Margin="24">
<TextBlock Text="RelayCommand 与 IoC"
FontSize="26" FontWeight="Bold" />
<TextBlock Margin="0,20,0,0" Text="姓名:" />
<TextBox Width="260" HorizontalAlignment="Left"
Text="{Binding CommandIoc.Name, UpdateSourceTrigger=PropertyChanged}" />
<Button Margin="0,16,0,0" Width="160" HorizontalAlignment="Left"
Content="通过命令打招呼"
Command="{Binding CommandIoc.SayHelloCommand}" />
<TextBlock Margin="0,20,0,0"
Text="{Binding CommandIoc.Message}"
TextWrapping="Wrap" />
</StackPanel>
</TabItem>

<TabItem Header="4 属性特性">
<StackPanel Margin="24">
<TextBlock Text="通知属性特性"
FontSize="26" FontWeight="Bold" />
<TextBlock Margin="0,20,0,0" Text="姓:" />
<TextBox Width="260" HorizontalAlignment="Left"
Text="{Binding PropertyAttributes.FirstName, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Margin="0,12,0,0" Text="名:" />
<TextBox Width="260" HorizontalAlignment="Left"
Text="{Binding PropertyAttributes.LastName, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Margin="0,20,0,0"
Text="{Binding PropertyAttributes.FullName, StringFormat=完整姓名:{0}}" />
</StackPanel>
</TabItem>

<TabItem Header="5 命令与验证">
<StackPanel Margin="24">
<TextBlock Text="命令与数据验证"
FontSize="26" FontWeight="Bold" />
<TextBlock Margin="0,20,0,0" Text="姓名(至少两个字符):" />
<TextBox Width="300" HorizontalAlignment="Left"
Text="{Binding Validation.Name, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Margin="0,8,0,0"
Foreground="#B33A3A"
Text="{Binding Validation.ErrorMessage}"
TextWrapping="Wrap" />
<Button Margin="0,16,0,0" Width="160" HorizontalAlignment="Left"
Content="提交"
Command="{Binding Validation.SubmitCommand}" />
<TextBlock Margin="0,20,0,0"
Text="{Binding Validation.Status}"
TextWrapping="Wrap" />
</StackPanel>
</TabItem>

<TabItem Header="6 异步命令与消息">
<StackPanel Margin="24">
<TextBlock Text="异步命令与消息接口"
FontSize="26" FontWeight="Bold" />
<Button Margin="0,20,0,0" Width="180" HorizontalAlignment="Left"
Content="开始异步加载"
Command="{Binding AsyncMessage.LoadCommand}" />
<TextBlock Margin="0,20,0,0"
Text="{Binding AsyncMessage.Status, StringFormat=状态:{0}}" />
<TextBlock Margin="0,8,0,0"
Text="{Binding AsyncMessage.ReceivedMessage, StringFormat=收到消息:{0}}"
TextWrapping="Wrap" />
</StackPanel>
</TabItem>
</TabControl>
</Grid>
</Window>
MainWindow.xaml.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using CommunityToolkitDemo.ViewModels;
using Microsoft.Extensions.DependencyInjection;
using System.Windows;

namespace CommunityToolkitDemo
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = App.Services.GetRequiredService<MainViewModel>();
}
}
}
Services/IGreetingService.cs
1
2
3
4
5
6
7
namespace CommunityToolkitDemo.Services
{
public interface IGreetingService
{
string GetGreeting(string name);
}
}
Services/GreetingService.cs
1
2
3
4
5
6
7
8
9
10
namespace CommunityToolkitDemo.Services
{
public class GreetingService : IGreetingService
{
public string GetGreeting(string name)
{
return $"你好,{name}!这条消息来自 IoC 注入的服务。";
}
}
}
Messages/StatusMessage.cs
1
2
3
4
5
6
7
8
9
10
11
using CommunityToolkit.Mvvm.Messaging.Messages;

namespace CommunityToolkitDemo.Messages
{
public class StatusMessage : ValueChangedMessage<string>
{
public StatusMessage(string value) : base(value)
{
}
}
}
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
namespace CommunityToolkitDemo.ViewModels
{
public class MainViewModel
{
public PreparationViewModel Preparation { get; }
public ObservableDemoViewModel ObservableDemo { get; }
public CommandIocViewModel CommandIoc { get; }
public PropertyAttributesViewModel PropertyAttributes { get; }
public ValidationViewModel Validation { get; }
public AsyncMessageViewModel AsyncMessage { get; }

public MainViewModel(
PreparationViewModel preparation,
ObservableDemoViewModel observableDemo,
CommandIocViewModel commandIoc,
PropertyAttributesViewModel propertyAttributes,
ValidationViewModel validation,
AsyncMessageViewModel asyncMessage)
{
Preparation = preparation;
ObservableDemo = observableDemo;
CommandIoc = commandIoc;
PropertyAttributes = propertyAttributes;
Validation = validation;
AsyncMessage = asyncMessage;
}
}
}
ViewModels/PreparationViewModel.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using CommunityToolkit.Mvvm.ComponentModel;

namespace CommunityToolkitDemo.ViewModels
{
public class PreparationViewModel : ObservableObject
{
private string _status = "CommunityToolkit.Mvvm 已就绪";

public string PackageInfo => "CommunityToolkit.Mvvm 8.2.1";

public string Status
{
get => _status;
set => SetProperty(ref _status, value);
}
}
}
ViewModels/ObservableDemoViewModel.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using CommunityToolkit.Mvvm.ComponentModel;

namespace CommunityToolkitDemo.ViewModels
{
public partial class ObservableDemoViewModel : ObservableObject
{
[ObservableProperty]
private string _name = "小明";

[ObservableProperty]
private int _count;

public string Greeting => $"你好,{Name}";
}
}
ViewModels/CommandIocViewModel.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 CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkitDemo.Services;

namespace CommunityToolkitDemo.ViewModels
{
public partial class CommandIocViewModel : ObservableObject
{
private readonly IGreetingService _greetingService;

[ObservableProperty]
private string _name = "小明";

[ObservableProperty]
private string _message = "点击按钮,通过命令调用服务。";

public CommandIocViewModel(IGreetingService greetingService)
{
_greetingService = greetingService;
}

[RelayCommand]
private void SayHello()
{
Message = _greetingService.GetGreeting(Name);
}
}
}
ViewModels/PropertyAttributesViewModel.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
using CommunityToolkit.Mvvm.ComponentModel;

namespace CommunityToolkitDemo.ViewModels
{
public partial class PropertyAttributesViewModel : ObservableObject
{
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(FullName))]
private string _firstName = "张";

[ObservableProperty]
[NotifyPropertyChangedFor(nameof(FullName))]
private string _lastName = "三";

public string FullName => $"{FirstName}{LastName}";
}
}
ViewModels/ValidationViewModel.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
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace CommunityToolkitDemo.ViewModels
{
public partial class ValidationViewModel : ObservableValidator
{
[ObservableProperty]
[NotifyDataErrorInfo]
[NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
[Required(ErrorMessage = "姓名不能为空")]
[MinLength(2, ErrorMessage = "姓名至少两个字符")]
private string _name = "小明";

[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(SubmitCommand))]
private bool _isBusy;

[ObservableProperty]
private string _status = "等待提交";

public string ErrorMessage =>
string.Join(";", GetErrors().Select(error => error.ErrorMessage));

public ValidationViewModel()
{
ErrorsChanged += (_, _) => OnPropertyChanged(nameof(ErrorMessage));
}

private bool CanSubmit()
{
return !IsBusy && !HasErrors && !string.IsNullOrWhiteSpace(Name);
}

[RelayCommand(CanExecute = nameof(CanSubmit))]
private void Submit()
{
Status = $"提交成功:{Name}";
}
}
}
ViewModels/AsyncMessageViewModel.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
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkitDemo.Messages;
using System.Threading.Tasks;

namespace CommunityToolkitDemo.ViewModels
{
public partial class AsyncMessageViewModel : ObservableRecipient, IRecipient<StatusMessage>
{
[ObservableProperty]
private string _status = "等待开始";

[ObservableProperty]
private string _receivedMessage = "还没有收到消息";

public AsyncMessageViewModel()
{
IsActive = true;
}

[RelayCommand]
private async Task LoadAsync()
{
Status = "正在加载...";
await Task.Delay(1200);
Status = "加载完成";
WeakReferenceMessenger.Default.Send(new StatusMessage("后台任务已经完成"));
}

public void Receive(StatusMessage message)
{
ReceivedMessage = message.Value;
}
}
}
CommunityToolkitDemo.Tests/Program.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
using CommunityToolkitDemo.Services;
using CommunityToolkitDemo.ViewModels;
using System;

var observable = new ObservableDemoViewModel();
observable.Name = "小红";
Console.WriteLine("可观察属性:" + observable.Greeting);

var command = new CommandIocViewModel(new GreetingService());
command.Name = "小明";
command.SayHelloCommand.Execute(null);
Console.WriteLine("命令与 IoC:" + command.Message);

var properties = new PropertyAttributesViewModel();
properties.FirstName = "李";
properties.LastName = "四";
Console.WriteLine("属性特性:" + properties.FullName);

var validation = new ValidationViewModel();
Console.WriteLine("验证初始可提交:" + validation.SubmitCommand.CanExecute(null));
validation.Name = "";
Console.WriteLine("空值可提交:" + validation.SubmitCommand.CanExecute(null));
Console.WriteLine("空值错误:" + validation.ErrorMessage);
validation.Name = "小明";
Console.WriteLine("合法值可提交:" + validation.SubmitCommand.CanExecute(null));
validation.SubmitCommand.Execute(null);
Console.WriteLine("提交结果:" + validation.Status);

var asyncMessage = new AsyncMessageViewModel();
await asyncMessage.LoadCommand.ExecuteAsync(null);
Console.WriteLine("异步命令状态:" + asyncMessage.Status);
Console.WriteLine("消息接收结果:" + asyncMessage.ReceivedMessage);