从 ListBox 中的选定项获取文本作为字符串

Getting text as string from selected item in ListBox

我有一个 ListBox,我试图将所选项目的值作为字符串获取,但我尝试的似乎都不起作用。以下是我为它设置 ListBox 和数据的方法:

public class Thing
    {
        public string Name { get; set; }
        public string Manufacturer { get; set; }
    }
System.Collections.ObjectModel.ObservableCollection<Thing> deviceList;

deviceList = new System.Collections.ObjectModel.ObservableCollection<Thing>()
        {
            new Thing{ Name="Amaze", Manufacturer="HTC"},
            new Thing{ Name="One X", Manufacturer="HTC"},
            new Thing{ Name="One X+", Manufacturer="HTC"},
            new Thing{ Name="Moto X", Manufacturer="Motorola"},
            new Thing{ Name="Moto G", Manufacturer="Motorola"},
            new Thing{ Name="OnePlus One", Manufacturer="Other"},
        };
System.ComponentModel.ICollectionView view = System.Windows.Data.CollectionViewSource.GetDefaultView(deviceList);
view.GroupDescriptions.Add(new System.Windows.Data.PropertyGroupDescription("Manufacturer"));
view.SortDescriptions.Add(new System.ComponentModel.SortDescription("Manufacturer", System.ComponentModel.ListSortDirection.Ascending));
view.SortDescriptions.Add(new System.ComponentModel.SortDescription("Name", System.ComponentModel.ListSortDirection.Ascending));
phoneListBox.ItemsSource = view;

这是XAML:

<ListBox Name="phoneListBox" Height="178" Margin="-25,25,5,0" SelectionChanged="phoneListBox_SelectionChanged" ScrollViewer.VerticalScrollBarVisibility="Visible">
 <ListBox.GroupStyle>
   <GroupStyle ContainerStyle="{StaticResource ContainerStyle}"/>
 </ListBox.GroupStyle>
 <ListBox.ItemTemplate>
  <DataTemplate>
   <TextBlock Text="{Binding Name}"/>
  </DataTemplate>
 </ListBox.ItemTemplate>
</ListBox>

我见过的最常见的方法是:

string selected = phoneListBox.GetItemText(phoneListBox.SelectedValue);

但 VS 根本无法将 GetItemText 识别为 属性 的 ListBox。

我也试过:

string selected = phonelistBox.SelectedItem.ToString();

但它不是 return 项目的实际文本。

我将 WPF 与 MahApps.Metro UI 一起使用,因此 ListBox 的属性可能与通用属性不同,但我不知道这将如何改变。任何建议表示赞赏。

你可以在selectionchanged事件中得到这样的名字,

 private void phoneListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
    Thing lbi = ((sender as ListBox).SelectedItem as Thing);
    string selected = lbi.Name.ToString();
 }