This project is read-only.
When writing MVVM, it's forbidden to use click handlers (or other UI events) in your view-model. But then should you react to events?

1. Start with creating a command like you are used to using MVVM. This command will be executed when the event occurs.
2. Add a reference to System.Windows.Interactivity.dll (ships with Catel). If you have used NuGet to add a reference, it is automatically included for you.
3. Add the following namespace definitions to your view declaration:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:Commands="clr-namespace:Catel.MVVM.Commands;assembly=Catel.Windows"

4. Use the following code to convert an event to a command:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="[YourEvent]">
        <catel:EventToCommand Command="{Binding [YourCommand]}" DisableAssociatedObjectOnCannotExecute="False" />
    </i:EventTrigger>
</i:Interaction.Triggers>

An example for a ListBox double click:

<ListBox ItemsSource="{Binding PersonCollection}" SelectedItem="{Binding SelectedPerson}">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseDoubleClick">
            <catel:EventToCommand Command="{Binding Edit}" DisableAssociatedObjectOnCannotExecute="False" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
            
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Label Content="{Binding FirstName}" />
                <Label Content="{Binding MiddleName}" />
                <Label Content="{Binding LastName}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Last edited Aug 4, 2011 at 7:12 AM by GeertvanHorrik, version 2

Comments

No comments yet.