本文介绍了在WPF(3.5sp1)中以编程方式设置ComboBox SelectedItem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在安装了Net Framework 3.5 sp1的wpf应用程序中设置SelectedItem programmaticaly时感到困惑。我仔细阅读了大约100篇帖子\topics,但仍然困惑((
我的xaml:

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>

如果我在其中一个项目中添加 IsSelected =True属性,项目选择WHY?
我在代码中尝试不同,仍然无法设置所选项:

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;

SelectedItem不是只读属性,为什么它不工作?
我认为这应该是一个微软的问题,而不是我的。或者我错过了什么?我试着玩ListBox,所有工作正常与相同的代码,我可以设置选择,获得选择等等。所以,我能做ComboBox?

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

推荐答案

要选择 ComboBox中的任何项目

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

这篇关于在WPF(3.5sp1)中以编程方式设置ComboBox SelectedItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 23:35