How can a button be bound to a command in a view model like in WPF with MVVM?
I don't think you can do it directly but how about using the button's click handler to invoke the command? It's not as clean as WPF but you still get your separation.
I'd recommend implementing INotifyPropertyChanged you can use it in WinForms as well as WPF. See here for an introduction and here for some additional information.
I've attached ICommand
objects to the Tag
property of Button
and MenuItem
objects before.
Then, I just see if I can cast and run it if I can, example:
private void button1_Click(object sender, EventArgs e)
{
ICommand command = ((Control)(sender)).Tag as ICommand;
if (command != null)
{
command.Execute();
}
}
For even an easier life, try subclassing the controls (e.g. Button
, MenuItem
)
You might find the WAF Windows Forms Adapter interesting. It shows how to apply the Model-View-ViewModel (MVVM) Pattern in a Windows Forms application. The Adapter implementation provides a solution for the missing Command support in Windows Forms.