KMC
KMC

Reputation: 20046

How to IsSelected a ComboBoxItem in code behind?

My ComboBoxItems are created in run-time by C# code. I can't figure out how to IsSelect a ComboBoxItems in code behind so it shows as default when ComboBox runs.

Basically I'm trying to convert the 2nd line of the following XAML to C# code

<ComboBox x:Name="comboBox1">
    <ComboBoxItem IsSelected="True"></ComboBoxItem>
</ComboBox>

To C#:

comboBox[0].IsSelected = "True" // this doesn't exit..

Upvotes: 0

Views: 4766

Answers (5)

Kishore Kumar
Kishore Kumar

Reputation: 21863

you can do that by using Items property of ComboBox

((ComboBoxItem)*testcombo*.Items[3]).IsSelected = true;

Upvotes: 0

biju
biju

Reputation: 18000

You can use like this

((ComboBoxItem)cmb.Items[1]).IsSelected = true;

Upvotes: 1

Grant Thomas
Grant Thomas

Reputation: 45083

Firstly, you can't access the items of a ComboBox through an indexer property as per the code in your question (comboBox[0] is invalid). So, you'll need to find the item you want, or alternatively, use the SelectedIndex property of the ComboBox itself, as suggested in another answer.

Secondly, IsSelected is of type bool, you therefore need to set it as such:

comboBoxItem.IsSelected = true;

The string literal of "True" is used in XAML as that is the nature of the language, and behind the scenes it uses converters to get the real value of the required type.

Upvotes: 1

use SelectedIndex property

comboBox1.SelectedIndex = 0;

Upvotes: 3

Related Questions