开发者

Problem with simple binding

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 t开发者_开发问答ype. 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 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.


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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜