MVVM in Windows 8 apps

56 sec read

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.

Windows 8 application Design Templates

Good news to all developers working on windows 8 applications!! There are 50 “Store Ready” templates for Windows 8 in the form of Visual...
kpantos
27 sec read

Windows 8 applications released

I’ve been working with windows 8 and Metro style apps since Microsoft released Its first private beta, I had to format my...
kpantos
1 min read

Privacy Policy Generator

For those of you that built Windows 8 applications one thing you’ll find out (probably the hard way as I did) is that you’ll...
kpantos
27 sec read

One Reply to “MVVM in Windows 8 apps”

Leave a Reply

Your email address will not be published. Required fields are marked *