9

When I use the Command in a Buttoncontrol the event handler which joined with Click event will never raised,

How can I use the Command and handle the Click event handler?

SRKX
  • 1,806
  • 1
  • 21
  • 42
Tomas1
  • 97
  • 1
  • 1
  • 4

3 Answers3

19

You could attach the ICommand to another property and execute it from the Click handler.

<Button x:Name="MyButton" Tag="{x:Static ApplicationCommands.Stop}" Click="MyButton_Click" />

and in the handler:

private void MyButton_Click(object sender, RoutedEventArgs e)
{
    var button = sender as Button;
    if (button != null)
    {
        var command = button.Tag as ICommand;
        if (command != null)
            command.Execute(button.CommandParameter);
    }
}

You'd also need to do some extra work if you wanted to keep the Command disabling behavior.

John Bowen
  • 24,213
  • 4
  • 58
  • 56
0

You need the EventToCommand behaviour in MVVMLight

Amsakanna
  • 12,254
  • 8
  • 46
  • 58
-3

A command is a kind of week event. The good thinks about commands is that you do not need to use events. Actually you do not need to use code behind at all and events if you use a Viewmodel pattern. See relay commands: http://blog.galasoft.ch/archive/2009/09/26/using-relaycommands-in-silverlight-and-wpf.aspx

Sirius
  • 9
  • 1
  • 1
    That's not right, you need to use code behind if you want you view to update things like SeletedItem in the ViewModel or handle in a specific way how selections work. – Ignacio Soler Garcia Aug 23 '11 at 12:46