Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep SelectedItem during filter of CollectionViewSource

I have a listbox that is being filter like this:

var view = CollectionViewSource.GetDefaultView(FilterSource);
view.Filter = FilterCode;

I am running into a problem where the SelectedItem is getting lost when the filter is used with viewmodel code like this:

VM
{
    public ObservableCollection<Model> Items{get;set;}
    public Model SelectedItem
    {
        get{return _selectedItem;}
        set{_selectedItem = value; NotifyPropertyChanged();}
    }
}

When the filter is applied, the SelectedItem is set to null. However, I want to keep that selected item unless the user actually clicks off of it. If the filter is removed, then the selected item should still be selected. The Model does have an IsSelected property, and I have been trying to think of ways to query for the IsSelected property. However, then the view's binding would not work the way I expect....or at least I am going in circles thinking it cannot

like image 537
Justin Pihony Avatar asked Nov 13 '22 03:11

Justin Pihony


1 Answers

My only way of accomplishing a fix here is the following in the SelectionChanged event:

if (e.AddedItems.Count == 0 && e.RemovedItems.Count >= 0)
    SpecialtyListBox.SelectedItem = e.RemovedItems[0];

But, this seems really hacky and forces that there must always be an item selected once an initial one is selected. In this case, that might work, but I would still like to see if anybody has a better solution?

like image 93
Justin Pihony Avatar answered Nov 14 '22 23:11

Justin Pihony