如何在WPF中正确绑定ListBoxItem? [英] How to properly bind a ListBoxItem in WPF?

查看:1145
本文介绍了如何在WPF中正确绑定ListBoxItem?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表框,我想在Foo对象中迭代一个Bars集合。

I have a listbox and I want to iterate over a collection of Bars in my Foo-object.

<ListBox DataContext="{Binding Path=Foo.Bars}" >
    <ListBox.Items>
        <ListBoxItem>
            <ContentControl DataContext="{Binding Path=.}" />
        </ListBoxItem>
    </ListBox.Items>
</ListBox>

这是我要使用的数据表。

This is the datatemplate I want to use.

<DataTemplate DataType="{x:Type Bar}">
        <Label Content="hello stackoverflow" />
</DataTemplate>

如果我通过使用工具Snoop( - >检查)我的应用程序,我注意到条款的整个集合绑定到ContentControl,而不是只有1

If I snoop (--> examine by using the tool Snoop) my application, I notice that the entire collection of Bars is bound to the ContentControl, in stead of just 1.

如何正确绑定所以这个集合的迭代是很好的?

How can I properly bind so the iteration over the collection goes fine?

推荐答案

你可以设置DataTemplate,WPF做所有的工作。将ItemsSource设置为 Bar 项目列表,然后为栏定义DataTemplate 项目。

You can just set the DataTemplate, and WPF does all the work. Set the ItemsSource to a list of Bar items, and then define a DataTemplate for Bar items.

<ListBox ItemsSource="{Binding Path=Foo.Bars}">
    <ListBox.Resources>
        <DataTemplate DataType="{x:Type Bar}">
            <Label Content="hello stackoverflow" />
        </DataTemplate>
    </ListBox.Resources>
</ListBox>

您还可以使用< ListBox.ItemTemplate>直接设置ItemsTemplate。 而不是< ListBox.Resources>

请参阅数据绑定概述在MSDN。

这篇关于如何在WPF中正确绑定ListBoxItem?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆