views:

460

answers:

2

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 ???

A: 

Is the ComboBox data bound?

If so you are probably better to do it through Binding rather than code ....

See this question ... http://stackoverflow.com/questions/1069577/wpf-listview-programmatically-select-item

Maybe create a new SelectableObject {Text = "Abc Theme", IsCurrentlySelected = True} Bind a collection of SelectableObjects to the ComboBox.

Essentially setting the IsCurrentlySelected property in the model and having UI update from the Model.

JTew