0

I'm trying to default the Combo Box selected item to index = 0 when the SelectedValue is Null. What is wrong with the data trigger ? Error: SelectedIndex is not recognized property

 <ComboBox x:Name="ACombobox" ItemsSource="{Binding Mode=OneWay, Source={StaticResource AList}}" DisplayMemberPath="TypeName" SelectedValuePath="TypeName" SelectedValue="{Binding AnObj.Type, Mode=TwoWay}" > <ComboBox.Triggers> <DataTrigger Binding="{Binding}" Value="{x:Null}"> <Setter Property="SelectedIndex" Value="0" /> </DataTrigger> </ComboBox.Triggers> </ComboBox> 

1 Answer 1

2

You should do it by creating a style trigger like below

<ComboBox x:Name="ACombobox" ItemsSource="{Binding Mode=OneWay, Source={StaticResource AList}}" DisplayMemberPath="TypeName" SelectedValuePath="TypeName" SelectedValue="{Binding AnObj.Type, Mode=TwoWay}" > <Style TargetType="ComboBox"> <Style.Triggers> <DataTrigger Binding="{Binding}" Value="{x:Null}"> <Setter Property="SelectedIndex" Value="0" /> </DataTrigger> </Style.Triggers> </Style> </ComboBox> 

The error says that it does not have a qualifying type name so by creating a style it apply to Combobox when you set the TargetType="ComboBox"


<ComboBox x:Name="ACombobox" ItemsSource="{Binding AList}" DisplayMemberPath="TypeName" SelectedValuePath="TypeName" SelectedValue="{Binding AnObj.Type, Mode=TwoWay}" > <ComboBox.Resources> <Style TargetType="ComboBox"> <Style.Triggers> <DataTrigger Binding="{Binding SelectedItem}" Value="{x:Null}"> <Setter Property="SelectedIndex" Value="0" /> </DataTrigger> </Style.Triggers> </Style> </ComboBox.Resources> </ComboBox> 

This works for me.


Example with StaticResource

 <Window.Resources> <x:Array x:Key="StringList" Type="System:String"> <System:String>Line 1</System:String> <System:String>Line 2</System:String> <System:String>Line 3</System:String> <System:String>Line 4</System:String> </x:Array> </Window.Resources> <ComboBox ItemsSource="{StaticResource StringList}" > <ComboBox.Resources> <Style TargetType="ComboBox"> <Style.Triggers> <Trigger Property="SelectedItem" Value="{x:Null}"> <Setter Property="SelectedIndex" Value="0"/> </Trigger> </Style.Triggers> </Style> </ComboBox.Resources> </ComboBox> 
Sign up to request clarification or add additional context in comments.

12 Comments

Abin: I got an exception : Items Collection must be empty before using Items Source.
Alist is a static resource defined in xaml. If I take this style out everything works fine and I get no errors.
Put your Style in ComboBox.Resources @AbinMathew . Either way I still can't get SelectedIndex working except on startup
Anyone knows how to make it work with a static resource ?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.