I’m trying to bind a collection to a ListBox using only XAML. It kind of works, but it’s only displaying MyProject.mainItem (which is the object type), instead of the actual values.
In the class that is assigned as the DataContext, I have this:
ItemCatalog.Add(new mainItem { Ref = "555555", ItemName = "First Item" });
In the XAML on the page that has the ListBox, I have this:
<ListBox ItemsSource="{Binding ItemCatalog}">
<DataTemplate>
<StackPanel Margin="0,0,0,17" Width="432">
<TextBlock Text="{Binding Ref}" TextWrapping="Wrap" Foreground="Black" />
<TextBlock Text="{Binding ItemName}" TextWrapping="Wrap" Margin="12,-6,12,0" Foreground="Black" />
</StackPanel>
</DataTemplate>
</ListBox>
It iterates through the entire ItemCatalog collection, but instead of displaying values such a First Item, it just shows the object’s type. thanks
If main item does not have a visual representation IE a data template. Then it will call the
ToString()of that object for its display. Which is why you’re seeing the object type.Why your data template is not working, is because you’ve tried to insert it as you would a
ListBoxItem.What you want to do is override the
ItemTemplateAlso you’ll want to set your
DataTypeproperty in theDataTemplateto the appropriate type.Hope it helps.