(资料图片)
0.说明CommunityToolkit.Mvvm8.1有一个重大更新的功能:源生成器功能,它极大简化我们的mvvm代码
但是本篇先总结一下原写法,下篇再总结源生成器功能
1.模型定义必须继承:ObservableObject
2.viewmodel代码实现几个关键点:
SetProperty是给属性赋值,并且通知更改通知ButtonClickCommand.NotifyCanExecuteChanged(); //通知命令 已经改变RelayCommand ButtonClickCommand //定义命令
namespace WpfDemoNet6.Demo{ public class DataViewModel1 : ObservableObject { private string title = "hello"; public string Title { get { return title; } set { //title = value; //PropertyChanged?.Invoke( this , new PropertyChangedEventArgs( "Name" ) ); //SetProperty 相当与设置值,并且PropertyChanged通知调用 SetProperty( ref title , value ); } } private bool isEnabled = false; /// /// 是否可以使用 /// public bool IsEnabled { get => isEnabled; set { SetProperty( ref isEnabled , value ); //通知命令 已经改变 ButtonClickCommand.NotifyCanExecuteChanged(); } } /// /// 命令 /// public RelayCommand ButtonClickCommand { get; } public DataViewModel1 () { //RelayCommand的第一个参数是命令调用语句 // 第2个参数(可选)是否允许使用 ButtonClickCommand = new RelayCommand( () => { //点击按钮,修改标题 Title = "hello(改)"; } , () => { return IsEnabled; } ); ButtonClickCommandPar = new RelayCommand( ( double val ) => { Title = $"hello(改):{val}"; } ); } public RelayCommand ButtonClickCommandPar { get; } }}
3.异步命令异步命令会自动控制控件的可见性,并且提供一个IsRunning属性可以判断异步是否完成
public DataViewModel1 (){ AsyncButtonClickCommand = new AsyncRelayCommand( RunTxtAsync ); AsyncButtonParClickCommand = new AsyncRelayCommand( RunTxtParAsync );}/*特别说明:异步命令会自动控制控件的可见性,并且提供一个IsRunning属性可以判断异步是否完成*//// /// 命令/// public IAsyncRelayCommand AsyncButtonClickCommand{ get;}private async Task RunTxtAsync (){ await Task.Delay( 4800 ); Title = "hello(Task改)";}/// /// 命令(带参数的)/// public IAsyncRelayCommand AsyncButtonParClickCommand{ get;}private async Task RunTxtParAsync ( double val ){ await Task.Delay( 4800 ); Title = $"hello(Task改):{val}";}