【问题标题】:How to properly bind a ListBoxItem in WPF?如何在 WPF 中正确绑定 ListBoxItem?
【发布时间】:2009-02-03 09:35:29
【问题描述】:

我有一个列表框,我想遍历我的 Foo 对象中的 Bars 集合。

<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,而不仅仅是 1。

如何正确绑定,以便对集合的迭代顺利进行?

【问题讨论】:

    标签: wpf data-binding xaml listview


    【解决方案1】:

    您可以只设置 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>
    

    您也可以直接使用 &lt;ListBox.ItemTemplate&gt; 而不是 &lt;ListBox.Resources&gt; 来设置 ItemsTemplate

    请参阅 MSDN 上的 Data Binding Overview

    【讨论】:

    • @Default 是的,那个链接已经烂掉了,对不起,我找不到替代品。这只是一篇讨论 WPF 中的绑定的文章。
    【解决方案2】:

    首先将您的命名空间添加到Window 元素(智能感知):

    xmlns:local="clr-namespace:yourenamespace"
    

    那么下面的XAMLWindow.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 中有一些对象实例的限制规则)。

    【讨论】:

    • 我建议您在问题中输入您的目标代码。我的回答中有一些语法错误,我更正了它(资源,而不是 Resouce,忘记了 GridView,我正在用手输入所有内容......)。
    • 实际上我使用的是列表框。我首先发布了 ListView,但我对其进行了编辑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 2017-05-07
    • 2011-07-29
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    相关资源
    最近更新 更多