2015-07-20 67 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