1. 属性绑定
private string title; public string Title { get;set; }
可用以下属性方式替换,生成器会自动生成;
[ObservableProperty] private string title;
另一种情况:命令
private bool isEnabled; public bool IsEnabled { get => isEnabled; set { isEnabled = value; OnPropertyChanged(nameof(IsEnabled)); //以上两句可由以下替代 //SetProperty(ref isEnabled, value); ButtonClickCommand.NotifyCanExecuteChanged(); } } public RelayCommand ButtonClickCommond { get; } public MainWindowViewModel() { ButtonClickCommond = new RelayCommand(() => { Debug.WriteLine("Button clicked."); Title = "good"; }, () => IsEnabled); }
可以通过以下属性方式替换(编译器自动生成以上代码):
[ObservableProperty] [NotifyCanExecuteChangedFor(nameof(ButtonClickCommand))] private bool isEnabled; [RelayCommand(CanExecute = nameof(IsEnabled))] //[RelayCommand(CanExecute = nameof(CanButtonClick))] private void ButtonClick() { Debug.WriteLine("Button clicked."); Title = "good"; } //private bool CanButtonClick() //{ // return IsEnabled; //}
异步命令:
[RelayCommand(CanExecute = nameof(IsEnabled))] private async Task ButtonClickAsync()//会自动将当前按钮设置CanExecute 设置为False退出时设置回True { await Task.Delay(1000); Title = "good"; }
2. xaml 内容为
绑定上下文:
d:DataContext="{d:DesignInstance local:MainWindowViewModel }"
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <TextBox Width="200" Text="{Binding Title}" /> <CheckBox Content="is Enabled" IsChecked="{Binding IsEnabled}" /> <Button Command="{Binding ButtonClickCommand}" Content="ok" /> </StackPanel>
3. 命令正在执行中:Command.IsRunning, Mode=OneWay(状态只读)
<CheckBox VerticalContentAlignment="Center" Content="Is Running" IsChecked="{Binding ButtonClickCommand.IsRunning, Mode=OneWay}" />
4. 当一个属性改变时同时通知另外一个变量也发生改变:NotifyPropertyChangedFor
[ObservableProperty] [NotifyPropertyChangedFor(nameof(Caption))] private string title = "hello world"; public string Caption => $"Title:{Title}";
5. 让 .NET Framework 下可以使用源生成器的方法:
方法一:
先创建.net6框架wpf项目,然后修改
双击项目修改TargetFramework,修改LangVersion8.0以上即可:
<TargetFramework>net472</TargetFramework>
<LangVersion>10.0</LangVersion>
方法二:
将.csproj 文件升级为.net6项目文件
方法三:
另外创建一个.net standard2.0的类库,通过这个类库中去使用,然后在主项目中应用类库中的数据
官方文档:https://learn.microsoft.com/zh-cn/dotnet/communitytoolkit/mvvm
标签:CommunityToolkit,nameof,string,Mvvm,Title,IsEnabled,private,学习,isEnabled From: https://www.cnblogs.com/chao-ye/p/17878902.html