WPF/C# Binding custom object list data to a ListBox?

后端 未结 4 519
情话喂你
情话喂你 2021-02-05 05:12

I\'ve ran into a bit of a wall with being able to bind data of my custom object list to a ListBox in WPF.

This is the custom object:

public          


        
相关标签:
4条回答
  • 2021-02-05 05:40

    In case anyone comes across this now via search, I just encountered pretty much the same issue in a C# UWP app.

    While the XAML bits in Nitin's answer above were necessary, they didn't fix the issue alone -- I also had to change my equivalent of Folder to be an ObservableCollection, rather than a List, to get the ListBox to show the property I needed.

    0 讨论(0)
  • 2021-02-05 05:43

    Each item in the list that ListBox shows automatically calls the ToString method to display it, and since you didn't override it, it displays the name of the type.

    So, there are two things you can do here.

    1. Override the ToString method like Sayse suggested.
    2. Use DataTemplate and bind each of your properties seperatly

    In your resource add the template with a key

            <DataTemplate x:Key="fileItemTemplate">
                <StackPanel>
                    <TextBlock Text="{Binding Name}"/>
                    <TextBlock Text="{Binding Path}"/>
                </StackPanel>
            </DataTemplate>
    

    and give it as your listbox ItemTemplate

    <ListBox x:Name="listboxFolder1" Grid.Row="1" BorderThickness="0"  ItemsSource="{Binding}" ItemTemplate="{StaticResource fileItemTemplate}">
    
    0 讨论(0)
  • 2021-02-05 05:56

    The easiest way is to override ToString on your FileItem, (The listbox uses this to populate each entry)

        public override string ToString()
        {
            return Name;
        }
    
    0 讨论(0)
  • 2021-02-05 06:00

    You will need to define the ItemTemplate for your ListBox

        <ListBox x:Name="listboxFolder1" Grid.Row="1" BorderThickness="0" 
         ItemsSource="{Binding}">
           <ListBox.ItemTemplate>
             <DataTemplate>
               <TextBlock Text="{Binding Name}"/>
             </DataTemplate>
           </ListBox.ItemTemplate>
         </ListBox>
    
    0 讨论(0)
提交回复
热议问题