0
votes

I am using WPF and Mvvm and my ListView has its ItemSource bound to an ICollectionView. How do I handle selected item change event?

Originally I had a DataGrid's ItemSource bind to the same ICollectionView and setup the collection's CurrentChanged event. Everything works fine, but not the case for a ListView.

2

2 Answers

4
votes

All you have to do, as Thomas mentioned is to bind the SelectedItem Attribute of the listbox to a property in the viewmodel. To make it clear, here's an example.

Here's my view

   <Grid x:Name="LayoutRoot" Background="White">
        <ListView ItemsSource="{Binding Contacts}" SelectedItem="{Binding SelectedContact, Mode=TwoWay}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding Name}" />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>   

And here's my ViewModel

public class MainViewModel: ViewModelBase
{
    ObservableCollection<ContactViewModel> contacts;
    ContactViewModel selectedContact;

    public ContactViewModel SelectedContact
    {
        get { return selectedContact; }
        set {
            selectedContact = value;
            base.OnPropertyChanged("SelectedContact"); 
        }
    } 

    public ObservableCollection<ContactViewModel> Contacts
    {
        get { return contacts; }
        set { 
            contacts = value;
            base.OnPropertyChanged("Contacts"); 
        }
    }
}

Everytime you try changing the selection in the listbox you'll step into the setter of the SelectedContact.

set 
{ 
     contacts = value;
     base.OnPropertyChanged("Contacts"); 
}

Through this, you'll know that the selected contact has changed.

Using the property SelectedContact, you'll also know which of the item in your collection is selected.

You can also bind a Collection property in the ViewModel to the SelectedItems attribute of the ListView if you want to implement multiple selection.

3
votes

Just bind the SelectedItem of the ListView to a property of your ViewModel