ComboBox ItemsSource changed => SelectedItem is ruined

前端 未结 8 932
忘掉有多难
忘掉有多难 2020-12-05 10:36

Ok, this has been bugging me for a while now. And I wonder how others handle the following case:



        
8条回答
  •  南笙
    南笙 (楼主)
    2020-12-05 11:15

    The standard ComboBox doesn't have that logic. And as you mentioned SelectedItem becomes null already after you call Clear, so the ComboBox has no idea about you intention to add the same item later and therefore it does nothing to select it. That being said, you will have to memorize the previously selected item manually and after you've updated you collection restore the selection also manually. Usually it is done something like this:

    public void RefreshMyItems()
    {
        var previouslySelectedItem = SelectedItem;
    
        MyItems.Clear();
        foreach(var myItem in LoadItems()) MyItems.Add(myItem);
    
        SelectedItem = MyItems.SingleOrDefault(i => i.Id == previouslySelectedItem.Id);
    
    }
    

    If you want to apply the same behavior to all ComboBoxes (or perhaps all Selector controls), you can consider creating a Behavior(an attached property or blend behavior). This behavior will subscribe to the SelectionChanged and CollectionChanged events and will save/restore the selected item when appropriate.

提交回复
热议问题