CommunityToolkit.MVVM 框架主要功能简述
环境
视频可以学习B站UP 十月的寒流大佬详解
官方文档 内容不太全 8.1.0 以后版本无详细说明
MVVM中最重要的的两个接口(原生&CommunityToolkit 对比, 可跳过)
1. INotifyPropertyChanged(原生)
class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
public void OnPropertyChanged(string PropertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
}
}
class MainWindowViewModel : ViewModelBase
{
private string title;
public string Title
{
get { return title; }
set
{
if (title != value)
{
title = value;
OnPropertyChanged(nameof(Title));
}
}
}
}
1. INotifyPropertyChanged(CommunityToolkit)
class ViewModelBase : ObservableObject
{
private string title;
public string Title
{
get { return title; }
set => SetProperty(ref title, value);
}
}
1. ICommand(原生)
class RealyCommand : ICommand
{
/// <summary>
/// 命令是否可以执行
/// </summary>
readonly Func<bool> _canExecute;
/// <summary>
/// 记录委托事件
/// </summary>
readonly Action _execute;
//public RelayCommond(Action action, Func<bool> canExecute)
//{
// _canExecute = canExecute;
// _execute = action;
//}
public event EventHandler CanExecuteChanged
{
add
{
if (_canExecute != null)
{
CommandManager.RequerySuggested += value;
}
}
remove
{
if (_canExecute != null)
{
CommandManager.RequerySuggested -= value;
}
}
}
public bool CanExecute(object parameter)
{
if (_canExecute == null)
return true;
return _canExecute();
}
public void Execute(object? parameter)
{
_execute();
}
}
1. ICommand(CommunityToolkit)
public MainViewModel()
{
// 初始化赋值命令
ButtonClickCommand = new RelayCommand(() => Title = "good bye", () => IsEnabled); // binding IsEnbled
}
MVVM 小例子
class MainViewModel : ObservableObject
{
private string title = "hello world";
public MainViewModel()
{
// 初始化赋值命令
ButtonClickCommand = new RelayCommand(() => Title = "good bye", () => IsEnabled); // binding IsEnbled
}
public string Title
{
get { return title; }
set => SetProperty(ref title, value); // binding
}
private bool isEnabled;
public RelayCommand ButtonClickCommand { get; set; }
public bool IsEnabled
{
get { return isEnabled; }
set
{
SetProperty(ref isEnabled, value); // binding
ButtonClickCommand.NotifyCanExecuteChanged(); // 通知binding 数据已刷新
}
}
}
<Grid TextElement.FontSize="20">
<StackPanel>
<TextBox Text="{Binding Title}" />
<CheckBox Content="Is Enabled" IsChecked="{Binding IsEnabled}"/>
<TextBox x:Name="textInput" />
<Button Command="{Binding ButtonClickCommand}"
Content="Show"
/>
<Button Margin="10" Height="20" BorderBrush="{StaticResource SolidColor}"/>
<Button Margin="10" Height="20" BorderBrush="{DynamicResource SolidColor}"/>
</StackPanel>
</Grid>
</Grid>