简体   繁体   中英

Combo box selection item returning an error

I created a combo item in xaml as follows:

    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>

When I get the chosen value in c# I get the "Null Reference exception error"

Here is my C# code.

Any ideas If I need to bound this? I thing the error has to do with the index of the value.

    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

This is wrong, int will never be null

 if (CmbBoxStart.SelectedIndex != null)

You must validate SelectedItem !=null

And it seems that SelectionBoxItem is used by the Combobox's ControlTemplate, perhaps you should use just Combobox.SelectedItem property.

string StrStartString = CmbBoxStart.SelectedItem.ToString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM