问题
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
回答1:
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?
回答2:
I had a similar problem, where the listboxes were shown as tabbed views. I solved the problem by creating a Converter to produce a Boolean flag for "isActive" and assigning it to CollectionViewSource.IsLiveFilteringRequested. This prevented the non-active list boxes from updating the selected item.
回答3:
You can fix this by creating a filter that always adds the current selected item to the filtered items. If this cannot be done directly, just hold the selected item in a separate variable.
来源:https://stackoverflow.com/questions/17100603/keep-selecteditem-during-filter-of-collectionviewsource