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
}
}