WPF 无法设置组合框的选定项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18416487/
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-13 09:29:14  来源:igfitidea点击:

WPF Unable to set Selected Item of a Combo box

c#wpfc#-4.0comboboxwpf-controls

提问by Tvd

I have a non-bound Combobox and I want to set its value at run time. I tried a lot but cannot achieve it. Here's the code :

我有一个非绑定组合框,我想在运行时设置它的值。我尝试了很多,但无法实现。这是代码:

<ComboBox  Background="#FFB7B39D" Grid.Row="1" Height="23" 
HorizontalAlignment="Right" Margin="0,26,136,0" 
Name="cboWellDiameter" VerticalAlignment="Top" Width="120">

     <ComboBoxItem Content="meter" IsSelected="True" />
         <ComboBoxItem Content="centimeter" />
</ComboBox>

In code, I am trying with :

在代码中,我正在尝试:

//VALUE of  sp.wellborediameterField_unit is centimeter
// Gives -1
int index = cboWellDiameter.Items.IndexOf(sp.wellborediameterField_unit);

Console.WriteLine("Index of well bore dia unit = " + index.ToString());  
cboWellDiameter.SelectedIndex = index;

// cboWellDiameter.SelectedItem = sp.wellborediameterField_unit;
// cboWellDiameter.SelectedValue = sp.wellborediameterField_unit;

SelectedItem & selectedValue has no impact. Why its not even able to find in Items ? How do I set it ?

SelectedItem 和 selectedValue 没有影响。为什么它甚至无法在 Items 中找到?我该如何设置?

Please help me, have several such non-bound and binded combos to set programmatically.

请帮助我,以编程方式设置几个这样的非绑定和绑定组合。

回答by McGarnagle

The issue is that your items are ComboBoxItems, not strings. So you have two options: one, use strings as the combo-box items (this allows you to set SelectedItem / SelectedValue = "meter" or "centimeter"):

问题是您的项目是 ComboBoxItems,而不是字符串。所以你有两个选择:一,使用字符串作为组合框项目(这允许你设置 SelectedItem / SelectedValue = "meter" or "centimeter"):

<ComboBox xmlns:clr="clr-namespace:System;assembly=mscorlib">
     <clr:String>meter</clr:String>
     <clr:String>centimeter</clr:String>
</ComboBox>

ortwo, set the SelectedItemby searching for the appropriate ComboBoxItem:

两个,SelectedItem通过搜索适当的来设置ComboBoxItem

cboWellDiameter.SelectedItem = cboWellDiameter.Items.OfType<ComboBoxItem>()
    .FirstOrDefault(item => item.Content as string == cosp.wellborediameterField_unit);