MVVM in Windows 8 apps

Having implemented Meteo and Zougla apps for windows 8 using MVVM Light I found that handling events wasn’t so straight forward.

While there are controls, like the Button control, that expose the Command and CommandParameter properties and can be bound to ICommand, (RelayCommand if you’re using MVVM light) typed properties in the ViewModel but there are many more that do not. What’s more a control may expose many events but have only one ICommand typed property for the most common interaction. Now in Silverlight, this can be easily fixed using the EventToCommand class that bridges the gap between events and commands. However, that doesn’t work in Windows 8.

Luckily though there is a replacement projects you could use to bind events to command properties in your ViewModels.

WinRtBehaviors

This project tries to fill the gap for people who really need behaviors to get cracking in XAML for Windows 8 apps and is also available as a NuGet package so can easily integrate it in your apps. The way you use it to trigger execution of the command when the user raises an event is pretty easy too:

<ListBox ItemsSource="{Binding ToDoItems}" Height="300" Name="MyListBox" 

            SelectedItem="{Binding SelectedToDo, Mode=TwoWay}" >

    <WinRtBehaviors:Interaction.Behaviors>

        <Win8nl_Behavior:EventToCommandBehavior Event="SelectionChanged" 

                                                Command="ItemClickCommand" 

                                                CommandParameter="{Binding SelectedToDo, Mode=TwoWay}"/>

    </WinRtBehaviors:Interaction.Behaviors>

    <ListBox.ItemTemplate>

        <DataTemplate>

            <TextBlock Text="{Binding Title}"></TextBlock>

        </DataTemplate>

    </ListBox.ItemTemplate>

</ListBox>

Notice that you can also use the CommandParameter property to pass data – again using a binding to pass data to your ViewModel.

Hope this helps.

 
Comments

Trackbacks for this post

Leave a Reply