2010-09-30 70 views
0

我想仅使用XAML将集合绑定到ListBox。它有些作品,但它只显示MyProject.mainItem(这是对象类型),而不是实际值。简单绑定的问题

在分配为在DataContext类的,我有这样的:

ItemCatalog.Add(new mainItem { Ref = "555555", ItemName = "First Item" }); 

在具有列表框页面上的XAML,我有这样的:

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

它循环通过整个ItemCatalog集合,但不是显示值如First Item,而是显示对象的类型。谢谢

+0

我以前没有使用silverlight,但有没有DataSource属性或“TextBlock”? – EJC 2010-09-30 03:45:05

回答

3

如果主项目没有可视化表示IE的数据模板。然后它会调用该对象的ToString()进行显示。这就是你看到对象类型的原因。

为什么你的数据模板不工作,是因为你试图插入它,就像你会ListBoxItem

你想要做的是覆盖ItemTemplate

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

而且你要在你的DataTemplateDataType属性设置为适当的类型。

希望它有帮助。

+0

谢谢,就是这样。我忘了添加'ItemTemplate'标签。 – XSL 2010-09-30 13:44:55

0

代码是说DataTemplate是列表框的项目之一。

尝试在<DataTemplate>周围添加<ListBox.ItemsTemplate>标签。