I want to set the SelectedIndex of ComboBox to 0 when the SelectedItem it is bound to is null by using DataTrigger. But it is not working. Where am I going wrong?
The xaml is as follows:
<ComboBox SelectedItem="{Binding MyObject.color_master, Mode=TwoWay}"
ItemsSource="{Binding MyEntities.color_master}"
DislayMemberPath="COLOR_DESCRIPTION" >
<ComboBox.Style>
<Style TargetType="ComboBox">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=MyObject.color_master}" Value="{x:Null}">
<Setter Property="SelectedIndex" Value="0" />
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.Style>
</ComboBox>
Here MyObject.color_master is null, but still the DataTrigger is not working !
My requirement is very simple, when nothing is selected in combobox, I want the first item to be selected.
It's only a guess but when you use both
SelectedItemandSelectedIndexyou create dependency on WPF implementation: "who wins?" is an implementation thing. Even if it's documented somewhere it would imply that every developer knows the order (which is not good too, because you never sure who will maintain your code).I think the simplest thing you can do here is use a single binding to
ViewModel'sSelectedColorIndexproperty and let theViewModelcalculate the value based oncolor_master. So the end result will look like this:Update: Since you said your view model can't be touched, here is another option. Write your own IValueConverter which will take an
MyObject.color_masterand convert it to the index:Where
ColorMasterToIndexConverterdefined in a reachable resource dictonary (for say, in the sameUserControl.Resourcescollection).