简体   繁体   中英

Selecting ListBox item returns null

I'm populating my list using data binding in WPF and everything is working fine. But I can't get the string of the selected item in my ListBox.

Here's my code of the button where I'm trying to get the value of selected Item.

private void hexButton_Click(object sender, RoutedEventArgs e)
    {
        if (imeiListBox.SelectedIndex == -1)
        {
            MessageBox.Show("Select IMEi from IMEI List!");
        }
        else
        {
            ListBoxItem myselectedItem= imeiListBox.SelectedItem as ListBoxItem;
            string text = myselectedItem.ToString();
        }
    }

And here's my XAML code of the ListBox.

 <ListBox x:Name="imeiListBox" 
          ItemsSource="{Binding Path=Devices}"  
          HorizontalAlignment="Left"  
          SelectionChanged="imeiListBox_SelectionChanged" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Path=Imei}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>

The problem is that string text = myselectedItem.ToString(); is returning null . How does one resolve that?

The imeiListBox.SelectedItem will be an object with the same type as the items you put in the ItemsSource of your ListBox , probably a Device object looking at your code.

You have to cast it like

imeiListBox.SelectedItem as Device;

instead.

SelectedItem doesn't return a ListBoxItem . It returns an instance of the type ( Device ?) where the Imei property is defined.

So you should cast to this type:

var myselectedItem= imeiListBox.SelectedItem as Device;
if (myselectedItem != null)
    string text = myselectedItem.Imei.ToString();

Or you could use the dynamic keyword:

dynamic myselectedItem= imeiListBox.SelectedItem;
string text = myselectedItem.Imei?.ToString();

Note that this will fail at runtime if SelectedItem returns anything else than an object with an Imei property. If you know the type, casting is preferable.

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