Bind RelayCommand to Button Click or CodeBehind

775 Views Asked by At

i want bind RelayCommand to Button Click event
(i know i can bind to command property but i want bind to click event)
how i can do this?
i used this code but not work:

private void Button_Clicked(object sender, RoutedEventArgs e) { 
FrameworkElement fe=sender as FrameworkElement;
((FirstViewModel)fe.DataContext).ShowSecondViewCommand();     
} 

Some of my personal controls do not have this property (command) so i cant bind my commands to command property

2

There are 2 best solutions below

0
FakeCaleb On

Assuming you have the correct xaml to bind a command. The following code will execute the command assigned to the button:

private void Button_Clicked(object sender, RoutedEventArgs e) { 
    var button = sender as Button;
    if(button.Command != null){
        button.Command.Execute(null);
    }
} 
0
Barracoder On

You need to use the InvokeCommandAction class to do this, or the EventToCommand class from MVVMLight

<Button xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
            <i:InvokeCommandAction Command="{Binding Path=SomeCommand, Mode=OneWay}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

Honestly though, this is not best practice. Is it not possible for your controls to simply expose a Command property instead?