How to properly bind a ListBoxItem in WPF?

2020-07-06 02:33发布

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>

This is the datatemplate I want to use.

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

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?

2条回答
Lonely孤独者°
2楼-- · 2020-07-06 02:57

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>

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

See Data Binding Overview at MSDN.

查看更多
甜甜的少女心
3楼-- · 2020-07-06 03:11

First add your namespace to the Window element (Intellisense) :

xmlns:local="clr-namespace:yourenamespace"

Then the following XAML ( in Window.Resources is a clean way to do it ) :

   <Window.Resources>

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

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

    </Window.Resources>

Place the Listbox :

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

But, it depends on your code-behind object, you have to set a constructor to initialise public properties within your object which are ObservableCollection<> preferably (There is some restriction rules with object instance in XAML).

查看更多
登录 后发表回答