簡體   English   中英

從列表框中的選定項目獲取文本作為字符串

[英]Getting text as string from selected item in 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可能具有與通用屬性不同的屬性,但是我不知道那會如何改變。 任何建議表示贊賞。

您可以在selectionchanged事件中獲得這樣的名稱,

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM