如何在WPF中正确绑定ListBoxItem?

10

我有一个列表框,我想在我的Foo对象的Bar集合上进行迭代。

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

这是我想要使用的数据模板。

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

如果我使用 Snoop 工具检查我的应用程序,我会注意到整个 Bars 集合被绑定到 ContentControl 上,而不仅仅是一个。

我该如何正确地绑定,以便对集合的迭代正常进行?

2个回答

8

您只需要设置DataTemplate,WPF会自动完成所有工作。将ItemsSource设置为Bar项目列表,然后为Bar项目定义一个DataTemplate。

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

你也可以直接使用<ListBox.ItemTemplate>而不是<ListBox.Resources>来设置ItemsTemplate。
请查看MSDN上的数据绑定概述

@Default 是的,那个链接已经失效了,我找不到替代品,很抱歉。它只是一篇关于 WPF 中绑定的文章。 - Cameron MacFarland

3
首先将你的命名空间添加到Window元素中(智能感知):
xmlns:local="clr-namespace:yourenamespace"

接下来的XAML代码(放在Window.Resources中)是一种简洁的方法:

   <Window.Resources>

        <ObjectDataProvider x:Key="DataProvider" ObjectType="{x:Type local:Foo}"/>

        <DataTemplate x:Key="Template" >
           <TextBlock Text="{Binding Bar}"/>
        </DataTemplate>

    </Window.Resources>

Listbox 放置于:

<ListBox DataContext="{Binding Source={StaticResource DataProvider}}" ItemsSource="{Binding Bars}" ItemTemplate="DynamicResource Template" />

但是,这取决于你的代码后端对象,你需要设置一个构造函数来初始化对象中的公共属性,最好使用ObservableCollection<>(在XAML中有一些对象实例的限制规则)。


1
我建议您在问题中输入您的目标代码。我的答案中有一些语法错误,我已经纠正了(是Resource,而不是Resouce,还忘记了GridView,我正在亲自手动输入所有内容…)。 - belaz
实际上我正在使用一个ListBox。我最初发布了ListView,但我进行了编辑。 - Natrium

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接