Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}"/>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading