关注墨瑾轩,带你探索编程的奥秘!
超萌技术攻略,轻松晋级编程高手
技术宝库已备好,就等你来挖掘
订阅墨瑾轩,智趣学习不孤单
即刻启航,编程之旅更有趣
核心思想:让ViewModel成为View的“灵魂伴侣”,而不是“陌生人”。
using CommunityToolkit.Mvvm.ComponentModel;
public class MainViewModel : ObservableObject
{
[ObservableProperty]
private string _greeting = "Hello, MVVM!";
}
ObservableObject
:这是CommunityToolkit.Mvvm的“魔法基类”,自带INotifyPropertyChanged
超能力(不用再手动写OnPropertyChanged
了)[ObservableProperty]
:这是“自动属性生成器”,会自动生成属性+OnPropertyChanged
通知(省时省力)_greeting
:这个字段会被自动转换为Greeting
属性,UI绑定时直接用{Binding Greeting}
就行// 传统写法(手动实现INotifyPropertyChanged)
private string _greeting;
public string Greeting
{
get => _greeting;
set
{
_greeting = value;
OnPropertyChanged();
}
}
CommunityToolkit.Mvvm的优势:一行代码搞定属性+通知,像用魔法棒一样简单!
痛点:数据绑定写得好像在玩“俄罗斯方块”,拼来拼去总是不对!
解决方案:用BindingContext
把View和ViewModel绑在一起,像给情侣配对戒指!
<Window x:Class="MyApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MVVM Demo" Height="350" Width="525">
<Window.DataContext>
<local:MainViewModel />
Window.DataContext>
<Grid>
<TextBlock Text="{Binding Greeting}" FontSize="24" HorizontalAlignment="Center" VerticalAlignment="Center"/>
Grid>
Window>
Window.DataContext
:这是View和ViewModel的“红线”,绑好了UI就能自动更新{Binding Greeting}
:绑定到ViewModel的Greeting
属性(因为用了[ObservableProperty]
)Ioc
容器管理ViewModel(后面会讲)终极目标:让按钮点击、数据验证、依赖注入都像“开外挂”一样简单!
实现方式:用RelayCommand
和Ioc
,像给代码装“自动挡”!
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
public class MainViewModel : ObservableObject
{
[ObservableProperty]
private string _greeting = "Hello, MVVM!";
[RelayCommand]
private void ChangeGreeting()
{
Greeting = "魔法生效了!"; // 点击按钮后,UI会自动更新
}
}
<Button Content="点击变魔法" Command="{Binding ChangeGreetingCommand}" HorizontalAlignment="Center" VerticalAlignment="Bottom" Margin="10"/>
[RelayCommand]
:这是“命令生成器”,自动生成ChangeGreetingCommand
属性和执行逻辑Command="{Binding ChangeGreetingCommand}"
:绑定到ViewModel的命令(不用写ICommand
接口了)AsyncRelayCommand
处理异步操作(比如加载数据)using CommunityToolkit.Mvvm.DependencyInjection;
public class MyService
{
public string GetMessage() => "来自服务的魔法信息!";
}
public class MainViewModel : ObservableObject
{
private readonly MyService _service;
public MainViewModel(MyService service)
{
_service = service;
}
[RelayCommand]
private void ShowMessage()
{
Greeting = _service.GetMessage(); // 通过依赖注入获取服务
}
}
using CommunityToolkit.Mvvm.DependencyInjection;
public static class App
{
public static void ConfigureServices()
{
var services = new ServiceCollection();
services.AddSingleton<MyService>();
Ioc.Default.ConfigureServices(services);
}
}
Ioc.Default.ConfigureServices
:这是CommunityToolkit.Mvvm的“依赖注入魔法”,让服务像快递一样自动送到ViewModel手里[IocConstructor]
自动注入依赖(更简洁)还记得那个在MVVM世界里“手忙脚乱”的你吗?现在你已经掌握了:
✅ 初始化魔法厨房:用ObservableObject
和[ObservableProperty]
简化属性绑定
✅ 绑定魔法通道:用DataContext
和{Binding}
让UI和ViewModel“心灵相通”
✅ 注入魔法能量:用[RelayCommand]
和Ioc
让命令和依赖“自动上线”