WPF Data Trigger not working - ComboBox selected index is not getting set to 0

3.1k views Asked by At

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.

1

There are 1 answers

1
Anvaka On BEST ANSWER

It's only a guess but when you use both SelectedItem and SelectedIndex you 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's SelectedColorIndex property and let the ViewModel calculate the value based on color_master. So the end result will look like this:

<ComboBox SelectedIndex="{Binding MyObjectViewModel.SelectedColorIndex, Mode=TwoWay}"  
          ItemsSource="{Binding  MyEntities.color_master}"
          DislayMemberPath="COLOR_DESCRIPTION" >
</ComboBox>

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_master and convert it to the index:

<ComboBox SelectedIndex="{Binding MyObject.color_master, Mode=TwoWay, Converter={StaticResouce ColorMasterToIndexConverter}}"  
          ItemsSource="{Binding  MyEntities.color_master}"
          DislayMemberPath="COLOR_DESCRIPTION" >
</ComboBox>

Where ColorMasterToIndexConverter defined in a reachable resource dictonary (for say, in the same UserControl.Resources collection).