[英]GetItemAt returning null value instead of ComboBoxItem
我有兩個帶有相同項目的ComboBox。 我正在嘗試通過索引獲取ComboBox的ComboBoxItem,但是返回了NULL值。 我的代碼是:
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;
}
}
}
任何想法...
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.