我有一个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();
但它不会返回该项目的实际文本。
我正在使用带有MahApps.Metro UI的WPF,因此ListBox可能有不同于通用属性的属性,但我不知道这会改变什么。任何建议都表示赞赏。