tags:

views:

314

answers:

4

How can a button be bound to a command in a view model like in WPF with MVVM?

A: 

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.

serialhobbyist
Yea, actually that is what I am doing now - I was just wondering if there was a reasonable way to do it with binding.
MarkB
A: 

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.

Matt Warren
+1  A: 

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)

Brett Veenstra
A: 

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.

jbe