Search code examples
c#wpfmvvm

WPF: How to bind Command-class?


I have a command that is in a separate class.

Command example:

class TestCommand : Command
{
    public override bool CanExecute(object? parameter) => true;

    public override void Execute(object? parameter) => Application.Current.MainWindow.Title = "test";
}

Command class:

abstract class Command : ICommand
{
    public event EventHandler? CanExecuteChanged
    {
        add => CommandManager.RequerySuggested += value;
        remove => CommandManager.RequerySuggested -= value;
    }
    
    public abstract bool CanExecute(object? parameter);
    
    public abstract void Execute(object? parameter);
}

The problem is that I cannot bind this command to a button or to another object in the View (except for the MenuItem). But if I declared a command in the view model, then I can bind it.

XAML file example

<Window.DataContext>
    <local:MainViewModel/>
</Window.DataContext>

<Grid>
    <button Command = "{Binding ???}"/>
    
    <!--but-->
    <MenuItem>
        <MenuItem.Command>
            <cmd:TestCommand/> <!--it works-->
        </MenuItem.Command>
    </MenuItem>
</Grid>

Is it possible to bind a command-class to a button?

I tried: edit DataContext, add RelativeSource


Solution

  • Make the TestCommand class public and add a property to your view model:

    public TestCommand TheCommand { get; } = new TestCommand();
    

    Then bind to this property:

    <Button Command = "{Binding TheCommand}"/>