在 WPF (3.5sp1) 中以编程方式设置 ComboBox SelectedItem

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2234063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:29:21  来源:igfitidea点击:

Programmatically set ComboBox SelectedItem in WPF (3.5sp1)

wpfcomboboxselecteditem

提问by Victor

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:

在安装了 Net Framework 3.5 sp1 的 wpf 应用程序中以编程方式设置 SelectedItem 时,我一直很困惑。我已经仔细阅读了大约一百个帖子 \topics 但仍然感到困惑((我的 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:

如果我在其中一项中添加IsSelected="True"属性 - 它不会将此项设置为选中状态。为什么 ?我尝试了不同的代码,但仍然无法设置所选项目:

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

SelectedItem 不是只读属性,为什么它不起作用?我认为那应该是微软的问题,而不是我的。或者我错过了什么???我尝试使用 ListBox,并且使用相同的代码都可以正常工作,我可以设置选择、获取选择等等......那么我可以用 ComboBox 做什么?也许一些技巧???

回答by Sooraj Kitchilu

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

要选择 中的任何项目ComboBox并将其设置为选定的默认项目,只需使用以下行:

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

回答by littlekujo

If i add the combobox and items programmatically, this works for me:

如果我以编程方式添加组合框和项目,这对我有用:

ComboBox newCombo = new ComboBox();

ComboBoxItem newitem = new ComboBoxItem();
newitem.Content = "test 1";
newCombo.Items.Add(newitem);
newitem = new ComboBoxItem();
newitem.Content = "test 2";
newCombo.Items.Add(newitem);
newitem = new ComboBoxItem();
newitem.Content = "test 3";
newCombo.Items.Add(newitem);

newCombo.SelectedItem =  ((ComboBoxItem)newCombo.Items[1]);
newCombo.Text = ((ComboBoxItem)newCombo.Items[1]).Content.ToString();

newStack.Children.Add(newCombo);

It also works if it set the ItemSourceproperty programmatically, then set the text to the selected value.

如果它以ItemSource编程方式设置属性,然后将文本设置为所选值,它也可以工作。

回答by ihatemash

Create a public property in your viewmodel for the theme list and one for the selected item:

在您的视图模型中为主题列表创建一个公共属性,为所选项目创建一个公共属性:

    private IEnumerable<string> _themeList;
    public IEnumerable<string> ThemeList
    {
        get { return _themeList; }
        set
        {
            _themeList = value;
            PropertyChangedEvent.Notify(this, "ThemeList");
        }
    }
    private string _selectedItem;
    public string SelectedItem
    {
        get { return _selectedItem; }
        set
        {
            _selectedItem = value;
            PropertyChangedEvent.Notify(this,"SelectedItem");
        }            
    }

bind your combobox in xaml to the properties like this:

将 xaml 中的组合框绑定到如下属性:

    <ComboBox 
        Name="cbTheme" 
        ItemsSource="{Binding ThemeList}"      
        SelectedItem="{Binding SelectedItem}">
    </ComboBox>

now all you do is add items to the ThemeList to populate the combobox. To select an item in the list, set the selected property to the text of the item you want selected like this:

现在您要做的就是将项目添加到 ThemeList 以填充组合框。要选择列表中的项目,请将 selected 属性设置为您要选择的项目的文本,如下所示:

    var tmpList = new List<string>();
    tmpList.Add("Sunrise theme");
    tmpList.Add("Sunset theme");

    _viewModel.ThemeList = tmpList;
    _viewModel.SelectedItem = "Sunset theme";

or try setting the selected item to the string value of the item you want selected in your own code if you want to use the code you currently have - not sure if it will work but you can try.

或者,如果您想使用您当前拥有的代码,请尝试将所选项目设置为您想要在自己的代码中选择的项目的字符串值 - 不确定它是否有效,但您可以尝试。

回答by vapcguy

If you know the index of the item you want to set, in this case it looks like you are trying to set index 1, you simply do:

如果您知道要设置的项目的索引,在这种情况下,您似乎正在尝试设置 index 1,您只需执行以下操作:

cbTheme.SelectedIndex = 1;

I found that when you don't know the index, that's when you have the real issue. I know this goes beyond the original question, but for Googlers on that count that want to know how to set the item when the index isn't known but the value you want to display IS known, if you are filling your dropdown with an ItemSourcefrom a DataTable, for example, you can get that index by doing this:

我发现当您不知道索引时,您就会遇到真正的问题。我知道这超出了最初的问题,但是对于那些想知道如何在索引未知但要显示的值已知时如何设置项目的 Google 员工来说,如果您使用ItemSourcefrom填充下拉列表a DataTable,例如,您可以通过执行以下操作来获取该索引:

int matchedIndex = 0;
if (dt != null & dt.Rows != null)
{
    if (dt.Rows.Count > 0)
    {
        foreach (DataRow dr in dt.Rows)
        {
            string myRowValue = dr["SOME_COLUMN"] != null ? dr["SOME_COLUMN"].ToString() : String.Empty;
            if (myRowValue == "Value I Want To Set")
                break;
            else
                matchedIndex++;
        }
     }
 }

And then you do simply do cbTheme.SelectedIndex = matchedIndex;.

然后你做简单的做cbTheme.SelectedIndex = matchedIndex;

A similar iteration of ComboBoxItemitems instead of DataRowrows could yield a similar result, if the ComboBoxwas filled how the OP shows, instead.

如果填充了 OP 显示的方式,则类似的ComboBoxItem项目迭代而不是DataRow行可能会产生类似的结果ComboBox

回答by user1063423

Acording Answer 4

根据答案 4

If you already add the Items in the Item source. Fire the PropertyChangedEvent of the selectet Value.

如果您已经在项目源中添加了项目。触发选择集值的 PropertyChangedEvent。

tmpList.Add("Sunrise theme"); 
    tmpList.Add("Sunset theme");
    PropertyChangedEvent.Notify(this,"SelectedItem");

回答by JTew

Is the ComboBox data bound?

ComboBox 数据是否绑定?

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

如果是这样,您可能最好通过绑定而不是代码来完成....

See this question ... WPF ListView Programmatically Select Item

看到这个问题... WPF ListView Programmatically Select Item

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

也许创建一个新的 SelectableObject {Text = "Abc Theme", IsCurrentlySelected = True} 将 SelectableObjects 的集合绑定到 ComboBox。

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

本质上是在模型中设置 IsCurrentlySelected 属性并从模型更新 UI。