1

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

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

在代码中,我正在尝试:

//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 没有影响。为什么它甚至无法在 Items 中找到?我该如何设置?

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

4

1 回答 1

7

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"):

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

or two, set the SelectedItem by searching for the appropriate ComboBoxItem:

cboWellDiameter.SelectedItem = cboWellDiameter.Items.OfType<ComboBoxItem>()
    .FirstOrDefault(item => item.Content as string == cosp.wellborediameterField_unit);
于 2013-08-24T08:25:13.783 回答