views:

63

answers:

2

Hi,

I am currently transforming a medium size WPF project to MVVM and I ran into a problem that I wasn't able to solve, yet. Maybe you could help me out?

The target framework is .NET 3.5.1.

I have a list view that gets its items from the underlying view model. That view model is exposing a command to remove the selected items from the list view. Therefore the command parameter is bound to the SelectedItems property of the list view.

<ListView ItemsSource="{Binding MyItems}"
          x:Name="MyListView"
          SelectionMode="Extended">
</ListView>
<Button x:Name="MyRemoveButton" 
        Content="Remove item" 
        Command="{Binding RemoveItemCommand}"
        CommandParameter="{Binding ElementName=MyListView, Path=SelectedItems}">

My intention is to execute this command not only when pressing a button, but also when the KeyUp event is fired on the list view and the pressed key is "delete".

I was close to finding the solution when I stumbled upon interaction triggers in this example:

http://joyfulwpf.blogspot.com/2009/05/mvvm-invoking-command-on-attached-event.html?showComment=1250325648481#c3867495357686026904

Now the problem with this demo is that the command parameter is the pressed key, but in my case I need the command parameter to be the SelectedItems property and I need the command to execute only on a specific key.

Is there any way to do this without much overhead and in the MVVM way?

Something like this would be awesome:

<i:Interaction.Triggers>
   <i:EventTrigger EventName="KeyUp">
      <local:CommandAction Command="{Binding RemoveItemCommand}"
                           CommandParameter={Binding ElementName=MyListView, Path=SelectedItems}
                           EventArgument="Key.Delete"/>
   </i:EventTrigger>
</i:Interaction.Triggers>
+2  A: 

To do it in the MVVM way you need to bind "SelectedItems" property of the ListView to your ViewModel, so you could use it from your commands and wouldn't need to pass it via CommandParameter.

Konstantin Oznobihin
I think I will try to do that using this:http://blog.functionalfun.net/2009/02/how-to-databind-to-selecteditems.html
HA
+1  A: 

How strict is your separation requirement? If you don't have designers using Blend, then put a call to a ViewModel method into the KeyUp or PreviewKeyUp event handler in your code-behind.

Rob Perkins
It's not that strict and this is definately an option, but for now I want a strict separation. This is kind of a proof of concept and I'm trying to explore the kinds of problems one can run into when using MVVM with a strict separation.
HA