2015-07-20 74 views
1

我有兩個組合框具有相同的項目。 我想通過索引獲取ComboBox的ComboBoxItem,但正在返回NULL值。 我的代碼是:GetItemAt返回null值而不是ComboBoxItem

var index = comboBox1.SelectedIndex; 
ComboBoxItem item = comboBox2.Items.GetItemAt(index) as ComboBoxItem; // item is null here 

//item = (ComboBoxItem)comboBox2.ItemContainerGenerator.ContainerFromItem(comboBox1.SelectedItem); 
//also tried above line but same result(null) 

和XAML:

<ComboBox Name="comboBox1" ItemsSource="{Binding ExistingModuleGroups}" SelectedItem="{Binding SelectedModuleGroup}" SelectionChanged="ComboBox1_SelectionChanged"> 
     <ComboBox.ItemTemplate> 
      <DataTemplate> 
        <TextBlock Text="{Binding Name}"/> 
      </DataTemplate> 
     </ComboBox.ItemTemplate> 
</ComboBox> 
<ComboBox Name="comboBox2" ItemsSource="{Binding ExistingModuleGroups}"> 
     <ComboBox.ItemTemplate> 
      <DataTemplate> 
        <TextBlock Text="{Binding Name}"/> 
      </DataTemplate> 
     </ComboBox.ItemTemplate> 

private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e) 
{ 
    if (e.AddedItems.Count > 0) 
    { 
      if (comboBox2.Items.Count > 0) 
      { 
       var index = comboBox1.SelectedIndex; 
       ComboBoxItem item = comboBox2.Items.GetItemAt(index) as ComboBoxItem; // item is null here 
       //item.IsEnabled = false; 
      } 

    } 
} 

任何想法...

+0

您選擇從組合框「1」指標,並試圖從組合框位於該索引得到一個項目「2」 - 這是由設計? – Krishna

+0

是@Krishna。它的設計。 – AmanVirdi

+0

並且您檢查了該索引是否小於combobox2.Items.counts的計數? – Krishna

回答

2

ItemsControl.Items屬性存儲的實際數據,而不是生成ComboBoxItems (除非你手動添加了ComboBoxItem類型的對象給Items集合)。

你已經接近你所評論的第二段代碼,但你正在尋找第二個組合中第一個組合的一個項目。由於你可能沒有對兩個組合使用相同的實例,所以這是行不通的。

正確的事情可能是這樣的。類似於您已經嘗試過,但有一些關鍵的差別:

var index = comboBox1.SelectedIndex; // Get the index from the first combo 
var item = (ComboBoxItem)comboBox2.ItemContainerGenerator 
       .ContainerFromIndex(index); // And get the ComboBoxItem from that index 
              // in the second combo 
+0

仍然無法使用。我更新了我的問題。 – AmanVirdi

+0

什麼是「不工作」?如果您的comboBox2至少包含與comboBox1相同數量的項目,則該代碼必須返回一個項目。你遇到了什麼錯誤?指數不大於零?鑄造失敗?它不會返回您期望的物品? – almulo

+0

comboBox2.Items.Count給出8.即使comboBox2.Items.GetItemAt(3)也給出null。沒有例外。 – AmanVirdi