Move the custom event handler from View to ViewModel


I have a custom event named OnVisualChartRangeChanged being fired from a UserControl called HistoricChartControl.

I am using the control in my main application like this:

    Title="MainWindow" Height="350" Width="525">


    <historicChart:HistoricChartControl >

I want that instead of having the event being handled in the view via the method VisualChartRangeChanged, the event be handled in the ViewModel.

How could I modify my code for this to happen? It would be helpful if you could post specific code as I am new to the WPF way of doing things.


The solution is to use Commands.

Since its a UserControl you may manipulate it to implement ICommandSource interface.

Then your UserControl will be able to bind a Command to ViewModel.

Once the event is being fired you simply call the command which will invoke Execute() method from the ViewModel.

For commanding in WPF I suggest you to read following link:

In your ViewModel you will have to offer a property of type ICommand.

EDIT Since you cannot manipulate your UserControl you will have to attach a command on it in XAML.

Interactivity is also an alternative to solve your issue. Take a look at this code:


<ListBox ...>
        <i:EventTrigger EventName="SelectionChanged">
            <i:InvokeCommandAction Command="{Binding SelectedItemChangedCommand}"/>

Interactivity is a third party dll from Microsoft Blend.

If you have nuget in visual studio you will be able to find that dll. If not here is the link: