DavieDave
DavieDave

Reputation: 1414

Delete ListView SelectedItem on Keypress

I would like to have a Key press of the Delete Key to fire off a DelegateCommand to actually delete the selecteditem at that point.

I am having troubles finding the right syntax to do this. I am using the INotifyPropertyChanged Implementation to bind to public propreties on my ViewModel.

Is there a way to do this? Seems like there should be.

I have an

ObservableCollection<Object> Objects

lets say with fields in each Object (i.e. name, address)

Thanks for any help

Upvotes: 3

Views: 5610

Answers (2)

emybob
emybob

Reputation: 1333

To get a command to fire from a keypress:

   <ListView ItemsSource="{Binding Path=Objects}" SelectedItem="{Binding Path=SelectedObject}">
        <ListView.InputBindings>
            <KeyBinding Key="Delete" Command="{Binding Path=MyCommand}"></KeyBinding>
        </ListView.InputBindings>
   </ListView>

For your selected item, have a property in your viewModel and bind the listView's SelectedItem to it.

Upvotes: 8

d.moncada
d.moncada

Reputation: 17402

You could use the 'event to command' feature in the MVVM Light Toolkit. By using this, you can set the keydown event to a command that gets fired in your ViewModel, along w/ the selected item's index as your param. Within your ViewModel, assuming your observablecollection is hooked up to your ListView right, you can then remove the selected item from the collection based on the index. Make sure the updatesourcetrigger on the items property of the listview is set to "property changed".

Upvotes: 0

Related Questions