如何在用户选择时从列表框中获取字符串值?

How to get string value from Listbox as user selected?

我无法在选择一项后从列表框中获取字符串值。

在我的列表框中,我有图像(盲源)和文本块(盲源)。

我的代码在 .xaml 页面:

        <ListBox Name="carListBox" Height="431" Canvas.Left="28" Canvas.Top="65" Width="446" SelectionChanged="ListBoxOnSelection">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <Image Name="brandImage" Source="{Binding Image}" Width="100" Height="150"></Image>
                        <Image Name="carImage" Source="{Binding Image}" Width="150" Height="150"></Image>
                        <TextBlock Name="textDisplay" Text="{Binding ShowDetail}" HorizontalAlignment="Center" VerticalAlignment="Center"></TextBlock>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

我的代码在 .xaml.cs 页面 (C#)

private void ListBoxOnSelection(对象发送者,SelectionChangedEventArgs args)

    {
       MessageBox.Show(carListBox.SelectedItem.ToString());
       string saveData = carListBox.SelectedItem.ToString();

    }

MessageBox 无法显示字符串值,用户选择后我无法获取值。

消息框显示[1]https://i.imgur.com/2VSjhgN.jpg

您必须先以某种方式获取 Car 对象,然后才能访问它的属性。

像这样:

private void ListBoxOnSelection(object sender, SelectionChangedEventArgs args)
{
 Car myCar=carListBox.SelectedItem as Car;
 if(myCar != null)
   MessageBox.Show(myCar.ShowDetail); //or any property.
}