2013-08-24 60 views
1

我有一個無界的組合框,我想在運行時設置它的值。我嘗試了很多,但無法實現。下面的代碼:WPF無法設置組合框的選定項目

//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沒有任何影響:

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

在代碼中,我與嘗試。爲什麼它甚至無法在物品中找到?我如何設置它?

請幫助我,有幾個這樣的非綁定和綁定組合編程設置。

回答

7

問題是您的項目是ComboBoxItems,而不是字符串。所以,你有兩種選擇:一,使用字符串作爲組合框中的項目(這允許您設置的SelectedItem /的SelectedValue =「米」或「釐米」):

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

二,設置SelectedItem通過搜索適當的ComboBoxItem

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

我沒有看到任何方法FirstOrDefault在項目中? Well OfType <>不是不允許的。 – Tvd

+0

@Tvd哦,對了,我使用Linq擴展爲了方便...添加'使用System.Linq;'以便能夠使用'FirstOrDefault'和'OfType' ... – McGarnagle

+0

噢,非常感謝。 – Tvd

相關問題