Let's first add RelayCommand class:
class RelayCommand: ICommand { private Action<object> _action; public RelayCommand(Action<object> action) { _action = action; } public bool CanExecute(object parameter) { return true; } public void Execute(object parameter) { if (parameter != null) { _action(parameter); } else { _action("Hello world"); } } public event EventHandler CanExecuteChanged; }
ICommand is an interface, and automatically you will receive methods which you have to implement. Now "click model":
public class MVVMButtonClickViewModel { public MVVMButtonClickViewModel() { MVVMClick = new RelayCommand(new Action<object>(ShowMessage)); } private ICommand m_ButtonCommand; public ICommand MVVMClick { get { return m_ButtonCommand; } set { m_ButtonCommand = value; } } public void ShowMessage(object obj) { MessageBox.Show("Test"); } }
and XAML:
<Window x:Class="MVVMButtonClick.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:MVVMButtonClick.ViewModel" Title="MainWindow" Height="350" Width="525"> <Window.DataContext> <local:MVVMButtonClickViewModel /> </Window.DataContext> <Grid> <Button Content="Button" HorizontalAlignment="Left" Margin="247,134,0,0" VerticalAlignment="Top" Width="75" Command="{Binding MVVMClick}"/> </Grid> </Window>
As you can see, in button node, we have attribute like: Command="{Binding MVVMClick}, and of course don't forget to add DataContext, like:
<Window.DataContext> <local:MVVMButtonClickViewModel /> </Window.DataContext>
Example you can download from here.