CommunityToolKit.Mvvm中按钮IsEnable属性不更新问题求助
解决方案
核心实现(基于CommunityToolkit.Mvvm)
先确保项目已安装CommunityToolkit.Mvvm NuGet包,再按以下结构编写ViewModel:
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; public class YourViewModel : ObservableObject { // 用[ObservableProperty]自动生成带变更通知的属性,字段名小写,生成的公开属性为大写开头(StringA、StringB) [ObservableProperty] [NotifyCanExecuteChangedFor(nameof(CreateFileCommand))] // 属性变更时自动通知命令更新可执行状态 private string _stringA = string.Empty; [ObservableProperty] [NotifyCanExecuteChangedFor(nameof(CreateFileCommand))] private string _stringB = string.Empty; // 用[RelayCommand]自动生成CreateFileCommand属性,无需手动声明命令字段 [RelayCommand(CanExecute = nameof(ValuesAreNotEmpty))] private async Task OnCreateFile() { // 这里写你的文件创建逻辑 await Task.Delay(1000); } // 判断两个输入是否都不为空 private bool ValuesAreNotEmpty() { return !string.IsNullOrWhiteSpace(StringA) && !string.IsNullOrWhiteSpace(StringB); } }
XAML绑定示例
按钮直接绑定自动生成的CreateFileCommand即可:
<TextBox Text="{Binding StringA, UpdateSourceTrigger=PropertyChanged}" /> <TextBox Text="{Binding StringB, UpdateSourceTrigger=PropertyChanged}" /> <Button Content="创建文件" Command="{Binding CreateFileCommand}" />
问题根源说明
你之前的问题主要出在两点:
- 手动声明命令字段和
[RelayCommand]自动生成的命令冲突,导致绑定的命令无法接收属性变更通知 - 没有在输入属性变更时触发命令的
CanExecute重新计算,[NotifyCanExecuteChangedFor]标记就是用来自动处理这个联动逻辑的
内容的提问来源于stack exchange,提问作者AdamMarty2000
相关产品推荐
相关产品推荐

