问题
I am playing with mvvm and wpf. Now, my total solution is MVVM-friendly. The only thing i have put in code behind is the "make new product" & close buttons on the mainview.
Now im adding a menubar, and i was wondering if i can put these "make new product" & close Items in code behind, or is this a no go?
Thanks in advance.
回答1:
The MVVM way to do it is commands. You can consider them as proxies between your declarative XAML and imperative VM.
- Create CreateNewProductCommand, implementing ICommand.
- Create a handler for the command performing the actual work as part of ICommand interface implementation (conventionally called On*** - OnCreateNewProductCommand) (you may want to pass paramteres for edit, which is supported by the interface too).
- Expose your command as property of your VM.
- Bind your menu item command (it'll likely have it, just search for properties containing Command) property to that command using standard binding syntax pointing to the relevant property created at a previous step.
This is not the only way to do it. There're more advanced techniques based on interactions/behaviors etc. Some of them would allow you to bypass command creation and bind your UI element event directly to the executable member of your VM.
来源:https://stackoverflow.com/questions/22690615/menubaritems-in-mvvm