Events Interactivity in WPF MVVM
In our last Article we have learned to create a sample application using WPF MVVM pattern including Inotify properties, Relay commands,Button click events.
In this article , we will learn how to fire other events in MVVM, for example if we need to fire double mouse click in WPF, we just need to create a new event handle on doublemouse click event but in MVVM it is not the case, because we cannot dorectly write the code for events in .cs form.So we need to use the RelayCommands for these events also, same as we have use dfor signle button click. So if we bind a command of button to a relay command, by default it would call a Singleleftmouseclick, but what we need to bind that command to doublemouseleftclick.
So for handling these types of events in MVVM we use :System.Windows.Interactivity;
Lets see how to use that:
Step 1: Just add a button control in MainWindow.xaml .
Step 2: Add reference "System.Windows.Interactivity" to solution explorer=>references as shown in below image.
Step 3: Now add the namespace for interactivity assembly in MainWindow.xaml and Xaml should look like as below:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication1" xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<TextBlock Text="{Binding GetText,UpdateSourceTrigger=PropertyChanged}" Width="100" Height="100" VerticalAlignment="Center"/>
<Button
IsDefault="True"
Content="Change Text" Width="100" Height="100" VerticalAlignment="Bottom"
>
</Button>
</Grid>
</Window>
Step 4: Lets create the triggerfor mouse double click as below:
In between the opening and closing tags of button add the trigger:
<Button
IsDefault="True"
Content="Change Text" Width="100" Height="100" VerticalAlignment="Bottom"
>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<i:InvokeCommandAction Command="{Binding ChangeTextCommand}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
Event Name should be same the event to want to fire, and Command should be bind to the Relay command in ViewModel which use want to excute when event occurs.
Note For RelayCommand please read our previous article : link
So now lets try running the application and see text should get changed on MousedoubleClick as shown in the below Images:
Before double Click:
After Double Click:
So this how we handle the events and we can use same approach for handling events of any control.
In our next articles we will learn how DataGrid, itemControls,Combobox and many more control works in MVVM.
Thank you.
Comments
Post a Comment