Programmatically set ComboBox SelectedItem in WPF (3.5sp1)

Victor  picture Victor · Feb 10, 2010 · Viewed 41.1k times · Source

I have been confused while setting SelectedItem programmaticaly in wpf applications with Net Framework 3.5 sp1 installed. I have carefully read about hundred posts \topics but still confused(( My xaml:

 <ComboBox name="cbTheme">
    <ComboBoxItem>Sunrise theme</ComboBoxItem>
    <ComboBoxItem>Sunset theme</ComboBoxItem> 
 </ComboBox>

If I add IsSelected="True" property in one of the items - it's dosn't sets this item selected. WHY ? And i was try different in code and still can't set selected item:

cbTheme.SelectedItem=cbTheme.Items.GetItemAt(1); //dosn't work
cbTheme.Text = "Sunrise theme"; //dosn't work
cbTheme.Text = cbTheme.Items.GetItemAt(1).ToString();//dosn't work
cbTheme.SelectedValue = ...//dosn't work
cbTheme.SelectedValuePath = .. //dosn't work
//and even this dosn't work:
ComboBoxItem selcbi = (ComboBoxItem)cbTheme.Items.GetItemAt(1);//or selcbi = new ComboBoxItem
cbTheme.SelectedItem = selcbi;

The SelectedItem is not readonly property, so why it wan't work? I think thats should be a Microsoft's problems, not my. Or I have missed something??? I have try playing with ListBox, and all work fine with same code, I can set selections, get selections and so on.... So what can I do with ComboBox ? Maybe some tricks ???

Answer

Sooraj Kitchilu picture Sooraj Kitchilu · Jun 30, 2012

To select any item in the ComboBox and to set it as default item selected just use the below line:

combobox.SelectedIndex = 0; //index should be the index of item which you want to be selected