How can a button be bound to a command in a view model like in WPF with MVVM?
相关问题
- How do I bind a DataGridViewComboBoxColumn to a pr
- Partial Form Class C# - Only display code view for
- Can we add four protocols to ServicePointManager.S
- How to properly handle form closing when using bac
- Filter Datagridview rows using TextBox
相关文章
- Sort TreeView Automatically Upon Adding Nodes
- Where does this quality loss on Images come from?
- Missing partial modifier on declaration of type
- PropertyGrid - Possible to have a file/directory s
- Best way to implement MVVM bindings (View <-> V
- Why do base Windows Forms form class with generic
- How to handle the TextChanged event only when the
- Difference between SuspendLayout and BeginUpdate
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.
You could create a generic command binding class that allows a command to be bound to any class that inherits from
ButtonBase
.The command binding can then be set up using the following code:
This is only the bare bones of my implementation to give you a start so naturally there are a few caveats:
ICommand
interface so may have to be altered if you have your own implementation of the command pattern.The generic constraint can also be changed to
Control
which exposes theClick
event and theEnabled
property which means commands can be bound to almost any Control.If you want to bind the command to the control using the designer, check this demo app where I show how to use MVVM in Windows Forms:
https://bitbucket.org/lbras/mvvmforms
The only code you have to write in the code-behind is the creation of the view model instance.
I was wondering if the same thing could be done and ended writing a simple CommandManager that queries the registered commands (on the Application.Idle event) and uses databinding to change the Enabled state of the control
This is the code I'm using right now:
and this is an exmaple of how to use it:
Also if you need the code, I blogged about it here
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.