简体   繁体   English

简单绑定的问题

[英]Problem with simple binding

I'm trying to bind a collection to a ListBox using only XAML. 我试图仅使用XAML将集合绑定到ListBox。 It kind of works, but it's only displaying MyProject.mainItem (which is the object type), instead of the actual values. 这种方法行得通,但是只显示MyProject.mainItem (这是对象类型),而不是实际值。

In the class that is assigned as the DataContext, I have this: 在分配为DataContext的类中,我有以下内容:

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

In the XAML on the page that has the ListBox, I have this: 在具有ListBox的页面上的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>

It iterates through the entire ItemCatalog collection, but instead of displaying values such a First Item , it just shows the object's type. 它遍历整个ItemCatalog集合,但是ItemCatalog显示诸如First Item类的值,它只是显示对象的类型。 thanks 谢谢

If main item does not have a visual representation IE a data template. 如果主要项目没有可视化表示IE,则为数据模板。 Then it will call the ToString() of that object for its display. 然后它将调用该对象的ToString()进行显示。 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 . 之所以无法使用数据模板,是因为您试图像ListBoxItem一样插入它。

What you want to do is override the ItemTemplate 您想要做的是覆盖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. 另外,您还要将DataTemplate中的DataType属性设置为适当的类型。

Hope it helps. 希望能帮助到你。

The code is saying that the DataTemplate is one of the items of the ListBox. 代码说DataTemplate是ListBox的项目之一。

Try adding a <ListBox.ItemsTemplate> tag around the <DataTemplate> . 尝试在<DataTemplate>周围添加<ListBox.ItemsTemplate>标记。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM