Binding to commands in WinForms

2019-01-22 19:54发布

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

标签: winforms mvvm
8条回答
Rolldiameter
2楼-- · 2019-01-22 20:42

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)

查看更多
Ridiculous、
3楼-- · 2019-01-22 20:49

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.

查看更多
登录 后发表回答