- A+
所属分类:.NET技术
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; /// <summary> /// 是否可以使用 /// </summary> public bool IsEnabled { get => isEnabled; set { SetProperty( ref isEnabled , value ); //通知命令 已经改变 ButtonClickCommand.NotifyCanExecuteChanged(); } } /// <summary> /// 命令 /// </summary> public RelayCommand ButtonClickCommand { get; } public DataViewModel1 () { //RelayCommand的第一个参数是命令调用语句 // 第2个参数(可选)是否允许使用 ButtonClickCommand = new RelayCommand( () => { //点击按钮,修改标题 Title = "hello(改)"; } , () => { return IsEnabled; } ); ButtonClickCommandPar = new RelayCommand<double>( ( double val ) => { Title = $"hello(改):{val}"; } ); } public RelayCommand<double> ButtonClickCommandPar { get; } } }
3.异步命令
异步命令会自动控制控件的可见性,并且提供一个IsRunning属性可以判断异步是否完成
public DataViewModel1 () { AsyncButtonClickCommand = new AsyncRelayCommand( RunTxtAsync ); AsyncButtonParClickCommand = new AsyncRelayCommand<double>( RunTxtParAsync ); } /* 特别说明:异步命令会自动控制控件的可见性,并且提供一个IsRunning属性可以判断异步是否完成 */ /// <summary> /// 命令 /// </summary> public IAsyncRelayCommand AsyncButtonClickCommand { get; } private async Task RunTxtAsync () { await Task.Delay( 4800 ); Title = "hello(Task改)"; } /// <summary> /// 命令(带参数的) /// </summary> public IAsyncRelayCommand<double> AsyncButtonParClickCommand { get; } private async Task RunTxtParAsync ( double val ) { await Task.Delay( 4800 ); Title = $"hello(Task改):{val}"; }
<!-- 特别说明:异步命令会自动控制控件的可见性,并且提供一个IsRunning属性可以判断异步是否完成 --> <Button Width="100" Height="30" Command="{Binding AsyncButtonClickCommand}" Content="异步" /> <TextBlock HorizontalAlignment="Center" FontSize="20" FontStyle="Italic" FontWeight="Bold" Foreground="Green" Text="loading......" Visibility="{Binding AsyncButtonClickCommand.IsRunning, Converter={StaticResource myboolconvert}}" />