C# GetItemAt返回空值而不是ComboBoxItem
我有两个相同项目的组合框。 我试图通过索引获取ComboBox的ComboBoxItem,但返回空值。 我的代码是:C# GetItemAt返回空值而不是ComboBoxItem,c#,wpf,C#,Wpf,我有两个相同项目的组合框。 我试图通过索引获取ComboBox的ComboBoxItem,但返回空值。 我的代码是: var index = comboBox1.SelectedIndex; ComboBoxItem item = comboBox2.Items.GetItemAt(index) as ComboBoxItem; // item is null here //item = (ComboBoxItem)comboBox2.ItemContainerGenerator.Contai
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>
任何想法…属性
ItemsControl.Items
存储实际数据,而不是生成的ComboBoxItems(除非您已将ComboxItem类型的对象手动添加到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
您正在从组合框“1”中选择索引,并试图从组合框“2”中获取该索引处的项目-这是设计的吗?是@Krishna。这是设计的。你检查了索引是否小于combobox2.Items.counts的计数?我检查过的所有内容。一切都好。两个组合框具有相同的项目编号、类型和顺序。我想禁用ComboBox2中的项目,如果它已经在Combox1中被选中,什么是“不工作”?如果您的comboBox2包含的项目至少与comboBox1相同,则该代码必须返回一个项目。你犯了什么错误?索引不大于零?铸造失败?它不会返回您期望的项目?comboBox2.Items.Count给出8。甚至连comboBox2.Items.GetItemAt(3)也给出了null。没有例外。我没有使用
GetItemAt
。。。我正在使用ItemContainerGenerator.ContainerFromIndex()
。如果comboBox2中有8个项目,并且您调用comboBox2.ItemContainerGenerator.ContainerFromIndex(3)
,我可以向您保证它不会返回null。从技术上讲,它应该像听起来那样“简单”。。。难道不是简单地item.IsEnabled=false
就行了吗?不过,这是另一个问题。也许你应该用这个来打开一个新的帖子。
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