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
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.
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.
ToString
method like Sayse suggested.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}">
The easiest way is to override ToString on your FileItem
, (The listbox uses this to populate each entry)
public override string ToString()
{
return Name;
}
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>