Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly bind a ListBoxItem in WPF?

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?

like image 479
Natrium Avatar asked Feb 03 '09 09:02

Natrium


2 Answers

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.

like image 87
Cameron MacFarland Avatar answered Oct 21 '22 11:10

Cameron MacFarland


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

like image 25
10 revs, 2 users 98% Avatar answered Oct 21 '22 11:10

10 revs, 2 users 98%