簡體   English   中英

如何顯示清單 <T> 在列表框中?

[英]How to display List<T> in List Box?

我嘗試顯示我在列表框上創建的列表,但我不知道如何

我有一堂課,在其中我將一本新書添加到列出C#代碼

public class Manager
{
    static List<Book> lstBook = new List<Book>();
    public void AddBookM(int isbn, string author, string des, string name, float price, ushort quantity, DateTime dateTime, string edition)
    {
        Book book = new Book(isbn, author, des, name, price, quantity,dateTime, edition, new List<string> { "" });
        lstBook.Add(book);
    }
}

現在在XAML中,我想在ListBox和AutoSuggestBox中的列表中看到書籍,我想在列表中搜索書籍,這將為完成XAML代碼打開可能性

        <AutoSuggestBox Name="SBSearchBtn" HorizontalAlignment="Center" Width="500" FontSize="20" BorderBrush="Black" Header="Search" PlaceholderText="Write here!" Margin="0,90,0,0" VerticalAlignment="Top" TextChanged="SBSearchBtn_TextChanged" QuerySubmitted="SBSearchBtn_QuerySubmitted" SuggestionChosen="SBSearchBtn_SuggestionChosen"/>
    <ListBox Name="SearchList" Width="500" Margin="140,194,860,400" Background="WhiteSmoke" FontSize="25"/>

為了在ListBox顯示項目,您需要執行以下操作:

首先,您需要為ListBox定義一個項目模板,以便您可以指定列表項目的外觀。 為簡單起見,我僅綁定Book類的nameauthor屬性。

XAML

<ListBox Name="SearchList">
    <ListBox.ItemTemplate>
       <DataTemplate>
           <StackPanel>
               <TextBlock Text="{Binding author}"></TextBlock>
               <TextBlock Text="{Binding name}"></TextBlock>
           </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

我建議使用ObservableCollection而不是僅使用List ,因為您要根據用戶搜索的內容來更新列表項。

private ObservableCollection<Book> lstBook = new ObservableCollection<Book>();

接下來,在Page的Loaded事件(或根據需要可能需要的任何事件)中,將ListBoxItemSource設置為您創建的ObservableCollectionlistBook )。

private void Page_Loaded(object sender, RoutedEventArgs e)
{
     //Setting item source of the list box
     SearchList.ItemsSource = lstBook;

     //Adding an entry to lstBook 
     AddBookM(1, "auth", "des", "name", 2.55f, 10, DateTime.Now, "edition");            
}  

現在,您應該看到一個條目已添加到列表視圖。 在這種情況下使用ObservableCollection的優點是,每當您進行更改(添加/刪除) ObservableCollection<Book> lstBook中的任何項目時,您的UI都會自動更新。

因此,當再次調用AddBookM()時,您將看到新條目也已添加到ListBox

希望這可以幫助 。

您需要手動編寫:

lstBook.Items.Add(book); // of course this is working only a ToString command to the Book class

您沒有說您在說什么ListBox,所以我只是假設您在談論Windows Forms庫中的ListBox。

希望我能幫到您!

暫無
暫無

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

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