如何在WPF中正确绑定ListBoxItem?

Nat*_*ium 10 data-binding wpf xaml listview

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

<ListBox DataContext="{Binding Path=Foo.Bars}" >
    <ListBox.Items>
        <ListBoxItem>
            <ContentControl DataContext="{Binding Path=.}" />
        </ListBoxItem>
    </ListBox.Items>
</ListBox>
Run Code Online (Sandbox Code Playgroud)

这是我想要使用的datatemplate.

<DataTemplate DataType="{x:Type Bar}">
        <Label Content="hello stackoverflow" />
</DataTemplate>
Run Code Online (Sandbox Code Playgroud)

如果我窥探( - >使用工具Snoop检查)我的应用程序,我注意到整个 Bars系列绑定到ContentControl,而不是1.

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

Cam*_*and 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>
Run Code Online (Sandbox Code Playgroud)

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

请参阅MSDN上的数据绑定概述.


bel*_*laz 3

首先将您的命名空间添加到Window元素(Intellisense):

xmlns:local="clr-namespace:yourenamespace"
Run Code Online (Sandbox Code Playgroud)

然后执行以下操作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>
Run Code Online (Sandbox Code Playgroud)

放置Listbox

<ListBox DataContext="{Binding Source={StaticResource DataProvider}}" ItemsSource="{Binding Bars}" ItemTemplate="DynamicResource Template" />
Run Code Online (Sandbox Code Playgroud)

但是,这取决于您的代码隐藏对象,您必须设置一个构造函数来初始化对象中的公共属性,最好是ObservableCollection<>(在 中对对象实例有一些限制规则XAML)。