views:

29

answers:

2

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

A: 

The code is saying that the DataTemplate is one of the items of the ListBox.

Try adding a <ListBox.ItemsTemplate> tag around the <DataTemplate>.

Cameron MacFarland
+3  A: 

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 ItemTemplate

<ListBox ItemsSource="{Binding ItemCatalog}">
    <ListBox.ItemTemplate>
         <DataTemplate/>
    </ListBox.ItemTemplate>
</ListBox>

Also you'll want to set your DataType property in the DataTemplate to the appropriate type.

Hope it helps.

Val
Thanks, that was it. I forgot to add the `ItemTemplate` tag.
SSL