此问题已在此处有答案:
WPF - How to force a Command to re-evaluate 'CanExecute' via its CommandBindings(6个回答)
Button Command CanExecute not called when property changed(1个答案)
9天前关闭
我刚开始使用和学习mvvm。我在ViewModel端设置的RelayCommand
不会禁用视图端的按钮。当我最初设置CanExecute
return false时,按钮似乎被禁用,键盘没有获得焦点。但是当CanExecute
在运行时返回false时,按钮不会被禁用,如下所示。错误可能在哪里?
<Button Content="Test"
Grid.Column="1"
Width="60"
Height="50"
Command="{Binding Path=TestCommand}"/>
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
using TestWpfApplication.Models;
namespace TestWpfApplication.ViewModels
{
public class PersonView : ObservableObject
{
private bool canExecute=true;
public event PropertyChangedEventHandler PropertyChange;
public bool _canExecute
{
get => canExecute;
set => SetProperty(ref canExecute,value);
}
private Person person;
public Person Person
{
get => person;
set => SetProperty(ref person, value);
}
public ObservableCollection<Person> Persons { get; } = new ObservableCollection<Person>();
public PersonView()
{
person = new Person();
Persons.Add(new Person() { Ad = "Fatih", Soyad = "Uyanık", Yas = 12 });
Persons.Add(new Person() { Ad = "eymen", Soyad = "Uyanık", Yas = 4 });
Persons.Add(new Person() { Ad = "Deneme1", Soyad = "Deneme1", Yas = 12 });
}
private ICommand testCommand;
public ICommand TestCommand => testCommand = new RelayCommand(Test, TestCanExecute);
private int Sayac = 0;
private bool TestCanExecute() => canExecute;
private void Test()
{
canExecute = Sayac++<3;
}
}
}
1条答案
按热度按时间bwleehnv1#
您可以轻松地绑定按钮的IsEnabled属性,并通过将该属性设置为false来禁用按钮。
关于ViewModel