本系列主要介绍微软社区工具包CommunityToolKit.Mvvm,是本人在观看B站UP主十月的寒流视频时的个人总结,真心感谢!学习C#的同学强力建议关注此UP,并观看其全部视频。
用 CommunityToolkit.Mvvm 加速 MVVM 开发流程_哔哩哔哩_bilibili
语言:C#
IDE:Microsoft Visual Studio Community 2022
框架:WPF,.net 8.0
目录
一.Mvvm模式下使用频率高的对象
1.1 ViewModelBase
2.1 RelayCommand
二、使用CommunityToolkit后的简化写法
2.1 部分简写
2.2 全部简写
三、Demo演示
3.1 Demo1,基础写法
3.2 Demo2,进阶写法
3.3 Demo3,异步方法
3.4 Demo4,小结
四、总结
4.1 ObservableObject
4.2 ObservableProperty
4.3 RelayCommand
4.3.1 CanExecute
4.3.1.1 属性名
4.3.1.2 方法名
4.3.2 AllowConcurrentExecutions
4.4 NotifyPropertyChangedFor
4.5 OnChanged,OnChanging
主要用于UI绑定,通过PropertyChangedEventHandler事件通知前台,以下是一个简单实现:
class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
class MainViewModel:ViewModelBase
{
private string title;
public string Title
{
get => title;
set
{
if (title != value)
{
title = value;
OnPropertyChanged(nameof(Title));
}
}
}
}
可以通过CallerMemberNameAttribute进行简化
class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
public void OnPropertyChanged([CallerMemberName]string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
class MainViewModel:ViewModelBase
{
private string title;
public string Title
{
get => title;
set
{
if (title != value)
{
title = value;
OnPropertyChanged();
}
}
}
}
绑定至UI控件的Command,用于执行事件及判断事件是否可以执行,以下是一个简单的实现:
class RelayCommand:ICommand
{
private readonly Action
class MainViewModel : ObservableObject
{
private string title;
public string Title
{
get => title;
set => SetProperty(ref title, value);
}
public RelayCommand ButtonClickCommand{get;}
}
[ObservableProperty]
string title = "Hello world";
[RelayCommand()]
void ButtonClick()
{
Title += "Goodbye";
}
显示效果:CheckBox控制Button的IsEnable,Button点击后改变TextBlock的内容。
ViewModel:
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
namespace Lesson1.ViewModels
{
public class MainViewModel1 : ObservableObject
{
private string title = "Hello,world";
public string Title
{
get => title;
set => SetProperty(ref title, value);
}
private bool isEnabled;
public bool IsEnabled
{
get => isEnabled;
set
{
SetProperty(ref isEnabled, value);
ButtonClickCommad.NotifyCanExecuteChanged();
}
}
public RelayCommand ButtonClickCommad { get; }
public MainViewModel1()
{
ButtonClickCommad = new RelayCommand(() => Title = "Goodbye", () => IsEnabled);
}
}
}
View: