This is my simplified example of
Klaus Loeffelmann article. With my example will just execute MessageBox.Show("Hello world");
First I have started new WinForms with .NET 8.0 support, and installed nuGet package
CommunityToolkit.Mvvm, then I have added new button, and the class SimpleCommandViewModel which inherits INotifyPropertyChanged:
public class SimpleCommandViewModel: INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
=> PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
private RelayCommand _sampleCommand;
public SimpleCommandViewModel()
{
_sampleCommand = new RelayCommand(ExecuteSampleCommand);
}
public void ExecuteSampleCommand()
=> MessageBox.Show("Hello world");
public RelayCommand SampleCommand
{
get => _sampleCommand;
set
{
if (_sampleCommand == value)
{
return;
}
_sampleCommand = value;
OnPropertyChanged();
}
}
}
Here notice:
new RelayCommand(ExecuteSampleCommand);
That means that by default my button is enabled, in comparsion of
Klaus Loeffelmann article:
new RelayCommand(ExecuteSampleCommand, CanExecuteSampleCommand);
Where his button will enabled only if CanExecuteSampleCommand is set to true.
Now, build it at least once.
Then in Properties -> DataBindings -> Command -> add new Object DataSource -> choose SimpleCommandViewModel, after choose SampleCommand from dropdown list. In Form Load event add code:
private void Form1_Load(object sender, EventArgs e)
{
simpleCommandViewModelBindingSource.DataSource = new SimpleCommandViewModel();
}
Example download from
here.