我有兩個組合框具有相同的項目。 我想通過索引獲取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;
}
}
}
任何想法...
您選擇從組合框「1」指標,並試圖從組合框位於該索引得到一個項目「2」 - 這是由設計? – Krishna
是@Krishna。它的設計。 – AmanVirdi
並且您檢查了該索引是否小於combobox2.Items.counts的計數? – Krishna