views:

5132

answers:

3

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?

+1  A: 

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

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

belaz
I implemented this, and it doesn't work.
Natrium
I suggest you to type your object code in your question. There was some syntax error in my answer, i correct it ( Resource, not Resouce, forgotten GridView, i'am typing it all with the hand... ).
belaz
actually I'm using a ListBox. I first posted ListView, but I edited that.
Natrium
+3  A: 

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 What does "{Binding}" mean? by Bea Stollnitz for more info.

Cameron MacFarland
A: 

none of the above do the magic trick... :-(

Natrium