How can a command on a ViewModel be invoked by a specific event of a button, such as MouseDoubleClick
?
相关问题
- VNC control for WPF application
- Listen for mouse released event on component on wh
- WPF Binding from System.Windows.SystemParameters.P
- XAML: Applying styles to nested controls
- How can I add a horizontal line (“goal line”) for
You need to do a lot of pluming yourself if you going to use Command and Event Binding from out of the box WPF. You can gain a lot of just using existing framework such as MVVM Light Toolkit, or Cliburn Micro that already provide command and even binding.
You can use the
EventTrigger
in the System.Windows.Interactivity namespace, which is part of the so-called Prism framework. If you're just getting started with MVVM, don't care too much for Prism by now, but keep it in mind for later. Anyway, you can steel theEventTrigger
It works like this:
Reference the assembly System.Windows.Interactivity.dll
In XAML, reference the namespace:
Then in your Button or any other control, add a EventTrigger like this:
This way, you bind your event to a Command on your DataContext.
Remark
To clarify the usage, here's a kind of real life example including the ViewModel. The fictional requirement is to allow the user to select an item in a list and then perform a command which takes the selected item as a parameter:
And that would be the ViewModel. Note how the parameter to the command is used, in the example with a generic version of a
DelegateCommand
object as you get it in every MVVM framework (sometimesRelayCommand
). This class takes the type of the required parameter as a generic parameter (hereItemViewModel
) and requires a method which takes an according parameter (hereExecuteDoSomethingWithItem(ItemViewModel ...)
). The rest is WPF magic: The oject to which theCommandParameter
property is bound in your XAML will be passed through as the parameter in yourExecute(...)
function.Have fun with learning MVVM, it's worth it.
you can use attached command behaviors
=> http://geekswithblogs.net/HouseOfBilz/archive/2009/08/21/adventures-in-mvvm-ndash-generalized-command-behavior-attachments.aspx