0

I have a particular collection which derives from ObservableCollection and this type of collection I am binding to ItemSource of ComboBox. The problem is that when the ItemSource is changed the SelectedItem is ruined so I need to hook up the event of ItemSource changed so I can manually set the SelectedItem property.
I have tried to use IsSynchronizedWithCurrentItem="True" but that results in selecting the first item from the list, which in my case is not what I want because the SelectedItem is not first in the list. I have created a Behavior and attached to ComboBox but I can not find an event to hook up the ItemSource changes, also I can not rely on property changes of ObservableCollection cause in most cases the Collection has changes on the items in the list and there are no new items added or removed. I will post below my implementation.

<ComboBox ItemsSource="{Binding DisplayZoneNumberSource}"
  SelectedItem="{Binding DisplayZoneNumberSelect, UpdateSourceTrigger=PropertyChanged}"
  ItemTemplateSelector="{StaticResource ComboBoxSourceTemplateSelector}"
  VerticalContentAlignment="Center">
    <i:Interaction.Behaviors>
        <local:ComboBoxItemSourceChangedBehavior/>
    </i:Interaction.Behaviors>
</ComboBox>
public class ComboBoxItemSourceChangedBehavior : Behavior<ComboBox>
{
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.SelectionChanged += AssociatedObject_SelectionChanged;
    }

    protected override void OnDetaching()
    {
        base.OnDetaching();
        AssociatedObject.SelectionChanged -= AssociatedObject_SelectionChanged;
    }

    private static void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        //Implementation
    }
}
Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
Gabriel Costin
  • 83
  • 1
  • 11

1 Answers1

1

If you create a custom class that inherits from ComboBox, there is a protected OnItemsSourceChanged method that you can override:

public class MyComboBox : ComboBox
{
    protected override void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
    {
        base.OnItemsSourceChanged(oldValue, newValue);
        //...
    }
}

Obviously this method won't get called when a property of an individual item in the source collection is set. If you need to this, you need to hook up an event handler for the PropertyChanged of each item whenever an item is added to or removed from the source collection. And this require your type of items to implement INotifyPropertyChanged or some other interface that has a similar event.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • Is there any event like `OnItemsSourceChanging` ? Because I can not use the one in the answer because it is too late and `SelectedItem` is already null – Gabriel Costin Nov 27 '19 at 16:34