Reputation: 2319
I would like to know how I can directly call a method of my controller from "Click" event button in my view without put code in my view
<Button Click="?"/>
I don't want to generate a method in my view just to call another method (Unless i have to).
Thanks
Upvotes: 0
Views: 395
Reputation: 26078
Commands are the usual answer to this problem. Unfortunately it takes a little boilerplate to get going, here is a really simple example:
public class MyViewModel
{
public MyCommand ButtonClick { get; set; }
public MyViewModel()
{
ButtonClick = new MyCommand();
ButtonClick.CanExecuteFunc = ButtonClickCanExecute;
ButtonClick.ExecuteFunc = ButtonClickFunc;
}
public bool ButtonClickCanExecute(object parameter)
{
return true;
}
public void ButtonClickFunc(object parameter)
{
// Do stuff here
}
}
public class MyCommand : ICommand
{
public event EventHandler CanExecuteChanged;
public Predicate<object> CanExecuteFunc { get; set; }
public Action<object> ExecuteFunc { get; set; }
public bool CanExecute(object parameter)
{
return CanExecuteFunc(parameter);
}
public void Execute(object parameter)
{
ExecuteFunc(parameter);
}
}
You can add more logic into the CanExecute
besides return true if you like, then you can just reuse the MyCommand
class for any other commands you have going on in your UI. To bind your button you just need to write simply:
<Button Command="{Binding ButtonClick}">Action</Button>
Upvotes: 1