locked
combobox default selecteditem RRS feed

  • Question

  • Hi all,

    I am using a combobox in my silverlight wcf ria service application. combobox is binded to a service class

                <ComboBox Width="125" Height="30" Margin="11,0,0,0"  x:Name="LanguageCombo"  SelectionChanged="LanguageCombo_SelectionChanged"  >
                    <ComboBox.ItemTemplate>
                        <DataTemplate>
                            <StackPanel Orientation="Horizontal">
                                <TextBlock Text="{Binding LangNameEnglish}" />
                                <!--<TextBlock Text="{Binding LastName}" Margin="5,0,0,0" />-->
                            </StackPanel >
        </DataTemplate>
                    </ComboBox.ItemTemplate>
                </ComboBox>

    in code:

    TranslationContext ctx=new TranslationContext();
               LoadOperation<Language> prd = ctx.Load(ctx.GetLanguagesQuery());
                LanguageCombo.ItemsSource = prd.Entities;

    In the language table,i have 3 values: english,arabic and swedish.

    I am getting all three values in combobox. But the issue is when the page loads combobox is not showing the default item selected. its just blank and when i click it it drop out to show 3 values.

    I need to select the first item,"English" as selected whenever i enters to this page. or i need to set the seleted index to zero.How can i do this?

    When i set LanguageCombo.SelectedIndex=0; it shows error

    Specified argument was out of the range of valid values.
    Parameter name: SelectedIndex




    Monday, October 24, 2011 4:33 AM

Answers

  • The combobox needs to be set to an object, not a value. Wherever you are defining your data, you need to have a language object that is set to english, then set the SelectedItem="{Binding DefaultLanguageObject, Mode=TwoWay}"  When that selection changes, the SelectedItem object "DefaultLanguageObject" will be where you get the selected value.

    Monday, October 24, 2011 9:02 AM

All replies

  • Make sure that your loaddataoperation is completed before setting the selectedindex since selectedindex in codebehind is depended of values inside the combobox.

    Or just do as jeanine says with XAML binding and object...

    Monday, October 24, 2011 4:58 AM
  • The combobox needs to be set to an object, not a value. Wherever you are defining your data, you need to have a language object that is set to english, then set the SelectedItem="{Binding DefaultLanguageObject, Mode=TwoWay}"  When that selection changes, the SelectedItem object "DefaultLanguageObject" will be where you get the selected value.

    Monday, October 24, 2011 9:02 AM
  • Hi,

    How to set this in code behind

    Thursday, November 24, 2011 5:17 AM