Search code examples
c#wpflistviewselecteditem

WPF ListView How to select a item from List<T>


I have a Listview where the datasource is a List<T> , when the content of the List<T> had changed I have to refresh the Listview and after that select the item I was selected before to refresh the Listview. This is my code that is not working well.

if (cbGroups.SelectedIndex!=-1)
{
    _GroupSelected = (Groups)cbGroups.SelectedValue;
}

_ItemSource = true;

// Refresh data source with the new records readed.

cbGroups.ItemsSource = Groups_DB.Records;

_ItemSource = false;

if (cbGroups.Items.Count >= 0 && _GroupSelected != null)
{
    _ItemSource = true;
    cbGroups.SelectedValue = _GroupSelected;
    int x = cbGroups.Items.IndexOf(_GroupSelected); // x is always -1
    _ItemSource = false;
}

So, someone can help me?


Solution

  • It seems obvious that the old _GroupSelected item is not an element of the new ItemsSource collection.

    Take a look at how the properties SelectValue and SelectedValuePath work together. Then restore the selection by using an appropriate "key" property as SelectedValue.

    Assuming a record has a unique Id property, set

    <ListView x:Name="cbGroups" SelectedValuePath="Id" ...>
    

    with code behind like this:

    var selectedId = cbGroups.SelectedValue;
    cbGroups.ItemsSource = Groups_DB.Records;
    cbGroups.SelectedValue = selectedId;