Search code examples
c#wpf

What to do to disable button when using mvvm?


I just started using and learning mvvm. A RelayCommand I set on the ViewModel side does not disable the button on the view side. When I initially set CanExecute return false the button appears to be disabled and the keyboard is not getting focus. But the button doesn't get disabled when CanExecute returns false at runtime like below. Where could the error be?

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

    }
}

Solution

  • you can easily bind the IsEnabled property of the button, and by setting that property to false the button will be disabled.

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

    On the ViewModel

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