I\'m trying to set a default selected value when ItemsSource
property changes on my ComboBox
My xaml :
has in addition to the current answers which led me on the way to my solution what i actually needed to accomplish is retrieving the last selected item when switching between itemsSources (plural)
from an article i found : "for each ItemsSource binding, a unique CollectionView is generated.."
i concurred that as long as the view exists each binding would generate its own CollectionView and thus hold a reference to CurrentItem and CurrentPosition if decorated with
IsSynchronizedWithCurrentItem="True"
so i created my own ChangePropertyAction Class :
public class RetriveLastSelectedIndexChangePropertyAction : ChangePropertyAction
{
public int LastSelectedIndex
{
get { return (int)GetValue(LastSelectedIndexProperty); }
set { SetValue(LastSelectedIndexProperty, value); }
}
public static readonly DependencyProperty LastSelectedIndexProperty =
DependencyProperty.Register("LastSelectedIndex", typeof(int), typeof(RetriveLastSelectedIndexChangePropertyAction), new UIPropertyMetadata(-1));
protected override void Invoke(object parameter)
{
var comboBox = this.AssociatedObject as ComboBox;
this.SetValue(LastSelectedIndexProperty, comboBox.Items.CurrentPosition);
}
}
and invoked it using PropertyChangedTrigger as follows :
<ComboBox ItemsSource="{Binding SelectedItemsSource, Mode=OneWay}"
x:Name="c1"
IsSynchronizedWithCurrentItem="True">
<i:Interaction.Triggers>
<ei:PropertyChangedTrigger Binding="{Binding ElementName=c1,Path=ItemsSource}">
<local:RetriveLastSelectedIndexChangePropertyAction
PropertyName="SelectedIndex"
Value="{Binding LastSelectedIndex}"
TargetName="c1"/>
</ei:PropertyChangedTrigger>
</i:Interaction.Triggers>
</ComboBox>
hope this helps if any one needing to retrieve their last selected item with out any messy code in their DataContext , enjoy.
Try changing your binding from:
<ei:PropertyChangedTrigger Binding="{Binding ItemsSource,RelativeSource={RelativeSource Self}}">
to
<ei:PropertyChangedTrigger Binding="{Binding ItemsSource,ElementName=c1}">
Try setting property IsSynchronizedWithCurrentItem to true
for your combobox and remove the trigger completely -
<ComboBox ItemsSource="{Binding SelectedItemsSource, Mode=OneWay}"
IsSynchronizedWithCurrentItem="True">
</ComboBox>