EventToCommandBehavior
The EventToCommandBehavior allows you to bind an event to an ICommand in the view model.
When working in more advanced development scenarios we often find ourselves leaning towards the MVVM pattern for producing cleaner, loosely coupled, easier to test code, but along with this comes the responsibility of ensuring that all controls we are using can follow this pattern. While it is very easy to work with the event-based model that exists across the .NET framework, events do not play well into the mindset of reducing traditional code-behind and instead handling logic within a viewmodel. This is where the Telerik EventToCommandBehavior class comes into use to allow your events to fire and your code to respond accordingly, all in the ViewModel without touching the code-behind of the UserControls.
Getting Started
The following example shows how to setup a RadListView control and bind its PointerPressed event to a command in the view model.
Example 1: Declare the RadListView control
Example 2: Create the view model class
Example 3: Bind a specific event to a desired command
telerikCore points to
xmlns:telerikCore="using:Telerik.Core"
RaiseOnHandledEvents
In case the event is RoutedEvent and it has been handled by the associated control, the command bound to the EventBinding won't be executed. To change this, set the RaiseOnHandledEvents property of the EventBinding to True.
Example 4: Set the RasedOnHandledEvents property
Command Parameters
To pass a parameter to the method that executes the command, set the CommandParameter property of the EventBinding object.
Example 5: Set the CommandParameter
Example 6: Modify the method in the ViewModel class
Example 7: Set the PassEventArgsToCommand property
Example 8: Modify the method to use the event arguments
Multiple Commands
The EventToCommandBehavior gives you the ability to add multiple EventBindings. You can easily bind multiple commands to a single event as well as a single command to multiple events. For example we can execute two commands in the ViewModel when the PointerPressed event of RadListView is fired:
Example 9: Set multiple event bindings
If you have multiple commands attached to a single event, the commands will be executed in the order they are defined in the EventBindings collection (from top to bottom).
Adding EventBinding Programmatically
The following example shows how to add an EventBinding object in code.