View model event bind to button click

7.7k views Asked by At

My Viewmodel has an event

public class TestViewModel 
{
    public event RoutedEventHandler Run;
}

I wanna trigger this event when user clicked on a button in view

How to bind this with a button in a view ?

2

There are 2 answers

0
brunnerh On BEST ANSWER

Routed events are meant for controls not view models, if you have something that should be executed upon a button click a command would be more suitable in my opinion, it can easily be bound to the Button.Command.

0
Maksim Gladkov On

I think, you should use DelegateCommand for such behavior.

In your View Model:

private DelegateCommand _runCommand;
public DelegateCommand RunCommand
{
    get
    {
        if (_runCommand == null)
            _runCommand = new DelegateCommand(Run, CanRun);

        return _runCommand;
    }
}

void Run()
{
    ... 
}

bool CanSaveAction()
{
    return true;
}

On your page:

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