【问题标题】:Getting text as string from selected item in ListBox从列表框中的选定项目中获取文本作为字符串
【发布时间】:2015-09-19 19:37:32
【问题描述】:

我有一个 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();

但它不返回项目的实际文本。

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

【问题讨论】:

  • 列表框中的项目是事物类的对象。所以如果你想要设备的名称,那么你必须使用string selected = phonelistBox.SelectedItem.Name;

标签: c# wpf xaml listbox mahapps.metro


【解决方案1】:

你可以在 selectionchanged 事件中获取这样的名字,

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    • 2012-11-16
    • 2011-02-26
    • 1970-01-01
    • 2012-05-08
    相关资源
    最近更新 更多