2016-10-01 28 views
0

我有以下XAML代碼:如何在這種情況下找到ComboBox值?

<ComboBox Name="cmbColors"> 
    <ComboBox.ItemTemplate> 
     <DataTemplate> 
     <StackPanel Orientation="Horizontal"> 
      <Rectangle Fill="{Binding Name}" Width="16" Height="16" Margin="0,2,5,2" /> 
      <TextBlock Text="{Binding Name}" /> 
      </StackPanel> 
     </DataTemplate> 
    </ComboBox.ItemTemplate> 
</ComboBox> 

和的.cs代碼:

public ComboBoxDataBindingSample() 
{ 
    InitializeComponent(); 
    cmbColors.ItemsSource = typeof(Colors).GetProperties(); 
} 

什麼是一種方法,我可以設置顯示爲「黑」當前組合框的值,而無需使用一個for循環找到它的索引?

+0

請記住這個組合框包含一個矩形和一個文本塊。做cmbColors.SelectedItem =「黑色」;不會將所選項目設置爲黑色。 – John

回答

0

你可以使用下面的代碼找到它的programmaticaly。

int index = comboBox1.Items.IndexOf(a); 

爲了獲得該項目本身,寫:

comboBox1.Items[index]; 
1

就算這樣簡單:

cmbColors.SelectedItem = "Black" ; 
0

這將通過代碼做

cmbColors.SelectedValue = "Black";