wpf 使用mvvm时如何禁用按钮?[副本]

7lrncoxx  于 2023-05-19  发布在  其他
关注(0)|答案(1)|浏览(109)

此问题已在此处有答案

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;
                                }

    }
}
bwleehnv

bwleehnv1#

您可以轻松地绑定按钮的IsEnabled属性,并通过将该属性设置为false来禁用按钮。

<Button Content="Test" Grid.Column="1" Width="60" Height="50" Command="{Binding Path=TestCommand}" IsEnabeled="{Binding IsButtonEnabled}"/>

关于ViewModel

bool isButtonEnabled;
    public bool IsButtonEnabled
    {
        get => isButtonEnabled;
        set => SetProperty(ref isButtonEnabled, value);
    }

相关问题