[英]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.