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

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

问题描述

我有一个列表框,我想遍历酒吧集合在我的Foo对象。

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>

这是我想要使用的DataTemplate。

This is the datatemplate I want to use.

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

如果我探听( - >使用该工具史努比检查)我的申请,我注意到,酒吧在整个集合在只有1代替绑定到ContentControl中,

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为酒吧项目列表,然后定义酒吧项目一个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>

您也可以通过使用直接设置ItemsTemplate &LT; ListBox.ItemTemplate&GT; 而不是&LT; ListBox.Resources&GT;

You could also set the ItemsTemplate directly by using <ListBox.ItemTemplate> instead of <ListBox.Resources>

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

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

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