Move the custom event handler from View to ViewModel

advertisements

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">

    <Window.DataContext>
        <viewModels:HistoricViewModel/>
    </Window.DataContext>

<Grid>
    <historicChart:HistoricChartControl >
        <historicChart:HistoricChartControl
            behaviours:ChartBehavior.OnVisualChartRangeChanged="VisualChartRangeChanged"/>
        </historicChart:HistoricChartControl>
</Grid>

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.

Thanks.


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:

http://msdn.microsoft.com/en-us/library/ms752308(v=vs.110).aspx

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:

 xmlns:I="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

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

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: http://www.nuget.org/packages/System.Windows.Interactivity.WPF/