-QuQ-
Articles11
Tags6
Categories0

Archive

CommunityToolkit.Mvvm

CommunityToolkit.Mvvm

基本使用及对比

绑定 Property

不使用 CommunityToolkit.Mvvm:

  1. 继承 INotifyPropertyChanged 接口
  2. 封装事件处理函数 OnPropertyChanged
  3. 绑定属性 setter 中调用事件处理函数
public class MainViewModel : INotifyPropertyChanged
{
	public string NextButtonText
	{
		get => field;
		set
		{
			field = value;
			OnPropertyChanged();
		}
	}

	public event PropertyChangedEventHandler? PropertyChanged = delegate { };

	public MainViewModel()
	{
		NextButtonText = "Next";
	}

	public void OnPropertyChanged([CallerMemberName] string propertyName = null)
	{
		PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
	}

}

使用 CommunityToolkit.Mvvm:

  1. ViewModel 标记为 partial 并继承 ObservableObject
  2. 属性添加 ObservableProperty 特性,并标记为 partial
public partial class MainViewModel : ObservableObject
{
    [ObservableProperty]
    public partial string NextButtonText { get; set; }

    [ObservableProperty]
    public partial string TextBoxText { get; set; }
}

绑定 Command

不使用 CommunityToolkit.Mvvm:

  1. 写个 RelayCommand 类,继承 ICommand 接口
  2. ViewModel 中定义 ICommand 与命令处理函数
  3. VIewModel 构造中实例化命令
// ViewModel
public class MainViewModel
{
	...

	public ICommand ChangeTextCommand { get; }

	public MainViewModel()
	{
		...
		ChangeTextCommand = new RelayCommand(ChangeText);
	}

	public void ChangeText()
	{
		NextButtonText = TextBoxText;
	}
}

// RelayCommand
public class RelayCommand : ICommand
{
	private readonly Action _execute;
	private readonly Func<bool> _canExecute;

	public RelayCommand(Action execute, Func<bool> canExecute = null)
	{
		_execute = execute ?? throw new ArgumentNullException(nameof(execute));
		_canExecute = canExecute;
	}

	public bool CanExecute(object parameter) => _canExecute == null || _canExecute();

	public void Execute(object parameter) => _execute();

	public event EventHandler CanExecuteChanged;

	public void RaiseCanExecuteChanged()
	{
		CanExecuteChanged?.Invoke(this, EventArgs.Empty);
	}
}

使用 CommunityToolkit.Mvvm:

  1. 函数添加 RelayCommand 特性
public partial class MainViewModel
{
	[RelayCommand]
	public void ChangeText()
	{
		NextButtonText = TextBoxText;
	}
}

如果不用 CommunityToolkit.Mvvm, 可以写一个 ViewModelBase 类统一实现框架代码

Author:-QuQ-
Link:http://qqqquq.me/2025/03/11/CommunityToolkit.Mvvm/
版权声明:本文采用 CC BY-NC-SA 3.0 CN 协议进行许可