开发者

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


use SelectedIndex property

comboBox1.SelectedIndex = 0;


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.


You can use like this

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


Did you tried ComboBox.SelectedItem? http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.selector.selecteditem.aspx


you can do that by using Items property of ComboBox

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜