开发者

Attach command with parameter to KeyUp event

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 ex开发者_如何学运维ecute 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>


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜