代码之家  ›  专栏  ›  技术社区  ›  Natrium

如何在WPF中正确绑定ListBoxItem?

  •  10
  • Natrium  · 技术社区  · 16 年前

    我有一个列表框,我想遍历Foo对象中的一组条。

    <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>
    

    如果我窥探(-->使用工具窥探检查)我的应用程序,我会注意到 将条绑定到ContentControl, 而不是只有1个

    如何正确绑定以使集合上的迭代顺利进行?

    2 回复  |  直到 16 年前
        1
  •  8
  •   Cameron MacFarland    12 年前

    您只需设置DataTemplate,WPF就可以完成所有工作。将ItemsSource设置为 Bar 酒吧 项目。

    <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>

    Data Binding Overview

        2
  •  3
  •   scottd    12 年前

    首先将命名空间添加到 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公司