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

偶尔善良 提交于 2019-12-03 01:24:10

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>

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

    public override string ToString()
    {
        return Name;
    }

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}">

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!