
CommunityToolkit.Mvvm
基本使用及对比
绑定 Property
不使用 CommunityToolkit.Mvvm
:
- 继承
INotifyPropertyChanged
接口 - 封装事件处理函数
OnPropertyChanged
- 绑定属性
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
:
ViewModel
标记为partial
并继承ObservableObject
- 属性添加
ObservableProperty
特性,并标记为partial
public partial class MainViewModel : ObservableObject
{
[ObservableProperty]
public partial string NextButtonText { get; set; }
[ObservableProperty]
public partial string TextBoxText { get; set; }
}
绑定 Command
不使用 CommunityToolkit.Mvvm
:
- 写个
RelayCommand
类,继承ICommand
接口 ViewModel
中定义ICommand
与命令处理函数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
:
- 函数添加
RelayCommand
特性
public partial class MainViewModel
{
[RelayCommand]
public void ChangeText()
{
NextButtonText = TextBoxText;
}
}
如果不用 CommunityToolkit.Mvvm
, 可以写一个 ViewModelBase
类统一实现框架代码