[英]Combo box selection item returning an error
我在xaml中創建了一個組合項,如下所示:
ComboBox x:Name="CmbBoxStart" HorizontalAlignment="Left" Height="108" Margin="10,191,0,0" VerticalAlignment="Top" Width="174" ItemsSource="{Binding}" SelectionChanged="CmbBoxStart_SelectionChanged" FontSize="25" IsDropDownOpen="False" BorderThickness="10" Background="{StaticResource ComboBoxBackgroundThemeBrush}" Foreground="{ThemeResource ComboBoxForegroundThemeBrush}" IsSynchronizedWithCurrentItem="False">
<x:String>0</x:String>
<x:String>1</x:String>
<x:String>2</x:String>
<x:String>3</x:String>
<x:String>4</x:String>
<x:String>5</x:String>
<x:String>6</x:String>
<x:String>7</x:String>
<x:String>8</x:String>
<x:String>9</x:String>
</ComboBox>
當我在C#中獲得選定的值時,我得到“空引用異常錯誤”
這是我的C#代碼。
有什么想法需要約束嗎? 我認為錯誤與值的索引有關。
private void CmbBoxStart_SelectionChanged(object sender,SelectionChangedEventArgs e)
{
if (CmbBoxStart.SelectedIndex != null)
{
string StrStartString = CmbBoxStart.SelectionBoxItem.ToString();
IntStartNumber = Convert.ToInt16(StrStartString);
//CmbBoxStart.GetValue(Item)
}
}
使用SelectedItem代替SelectedIndex
這是錯誤的,int永遠不會為null
if (CmbBoxStart.SelectedIndex != null)
您必須驗證SelectedItem !=null
似乎Combobox的ControlTemplate使用了SelectionBoxItem,也許您應該只使用Combobox.SelectedItem屬性。
string StrStartString = CmbBoxStart.SelectedItem.ToString();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.