Arfender
Arfender
CC#
Created by Arfender on 11/18/2024 in #help
CanExecuteChanged event
Hey. I am learning how to use Commands in C# and created simple command, to interact with my ViewModel (some notebook manager). If some notebook is selected, adding new note should be possible, if nothing is selected, the button binded with that command should be disabled. I have following code:
c#
using System.Windows.Input;
using EvernoteClone.Model;

namespace EvernoteClone.ViewModel.Commands;

internal class NewNoteCommand : ICommand
{
public NewNoteCommand(NotesVm vm)
{
Vm = vm;
}

private NotesVm Vm { get; set; }

public bool CanExecute(object? parameter)
{
var selectedNotebook = parameter as Notebook;
return selectedNotebook != null;
}

public void Execute(object? parameter)
{
if (parameter is Notebook selectedNotebook) {
Vm.CreateNote(selectedNotebook.Id);
}
}

public event EventHandler? CanExecuteChanged;
}
c#
using System.Windows.Input;
using EvernoteClone.Model;

namespace EvernoteClone.ViewModel.Commands;

internal class NewNoteCommand : ICommand
{
public NewNoteCommand(NotesVm vm)
{
Vm = vm;
}

private NotesVm Vm { get; set; }

public bool CanExecute(object? parameter)
{
var selectedNotebook = parameter as Notebook;
return selectedNotebook != null;
}

public void Execute(object? parameter)
{
if (parameter is Notebook selectedNotebook) {
Vm.CreateNote(selectedNotebook.Id);
}
}

public event EventHandler? CanExecuteChanged;
}
In the internet I found information, that CanExecuteChanged event should be connected via:
c#
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
c#
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
However, my code works fine (the button is enabling/disabling as expected), even when the event is not connected. I am confused. Can somebody explain me why?
1 replies