在现代 .NET 应用程序开发中,CommunityToolkit.Mvvm 提供了强大的命令实现机制,特别是 [RelayCommand] 特性和 IRelayCommand 接口,极大地简化了 MVVM 模式下的命令绑定和处理。

[RelayCommand] 特性允许你快速创建命令,无需手动编写样板代码。
C#using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
namespace App08
{
public partial class UserViewModel: ObservableObject
{
// 简单命令
[RelayCommand]
private void SaveUser()
{
// 保存用户逻辑
Console.WriteLine("用户已保存");
}
}
}
C#namespace App08
{
internal class Program
{
static void Main(string[] args)
{
var viewModel = new UserViewModel();
// 使用生成的命令属性
viewModel.SaveUserCommand.Execute(null);
Console.ReadKey();
}
}
}

支持带参数的命令,编译器自动生成对应的命令属性。
C#// 带参数命令
[RelayCommand]
private void DeleteUser(int userId)
{
Console.WriteLine($"删除用户:{userId}");
}
使用 async 关键字创建异步命令。
C#[RelayCommand]
private async Task LoadUserDataAsync()
{
// 模拟异步加载
await Task.Delay(1000);
Console.WriteLine("用户数据已加载");
}
通过 CanExecute 方法控制命令是否可执行。
C#public partial class UserViewModel
{
private bool _isUserSelected = false;
[RelayCommand(CanExecute = nameof(CanDeleteUser))]
private void DeleteSelectedUser()
{
Console.WriteLine("删除选中用户");
}
private bool CanDeleteUser() => _isUserSelected;
}
使用 CancellationToken 支持命令取消。
C#using System;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
namespace App08
{
public partial class UserViewModel : ObservableObject
{
// 将方法改为 public
[RelayCommand]
public async Task LongRunningTaskAsync(CancellationToken cancellationToken)
{
try
{
for (int i = 0; i < 100; i++)
{
// 检查是否已取消
cancellationToken.ThrowIfCancellationRequested();
await Task.Delay(100, cancellationToken);
Console.WriteLine($"进度:{i}%");
}
Console.WriteLine("任务完成");
}
catch (OperationCanceledException)
{
Console.WriteLine("任务已取消");
throw; // 重新抛出异常,让调用者知道任务被取消
}
}
}
}
C#namespace App08
{
internal class Program
{
public static async Task Main()
{
var viewModel = new UserViewModel();
// 创建一个CancellationTokenSource
using var cts = new CancellationTokenSource();
// 启动长时间运行的任务
var task = viewModel.LongRunningTaskAsync(cts.Token);
// 模拟用户在中途取消任务
await Task.Delay(500); // 等待一小段时间后取消
cts.Cancel();
try
{
await task;
}
catch (OperationCanceledException)
{
Console.WriteLine("主程序捕获:任务已取消");
}
Console.WriteLine("按任意键退出...");
Console.ReadKey();
}
}
}

CommunityToolkit.Mvvm NuGet 包CommunityToolkit.Mvvm 的 [RelayCommand] 特性极大地简化了命令创建,提供了强大且灵活的命令绑定机制。
本文作者:技术老小子
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!