Search code examples
wpfbindingcollectionsdatatemplate

WPF DataTemplate for Collection


I must now hang my head, for I have scoured the Google for hours and still have no clue what I'm doing wrong.

<DataTemplate DataType="{x:Type local:Controllers}">
    <ListBox>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <WrapPanel>
                    <TextBlock Text="{Binding Path=Port}" />
                </WrapPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</DataTemplate>

What I'm trying to do is to display an arbitrary number of controller objects in this list. "Controllers" is just an alias for "List<Controller>". "Port" is a property of each "Controller" object, but of course that's not showing up on the list. Items are being correctly added to the collection the list is based on (the collection is actually stored as the Content property of the ContentControl that is displaying this collection of objects), but no item in the collection itself is being displayed.

I thought at first that it might be an update issue--that the collection was being correctly displayed in its initial, empty state, but that isn't the case; if I start with the collection already populated, I still get no items.

Help me, Obi Wan. :(


Solution

  • You need to bind something to the ListBox. That something is just {Binding}, which refers to the instance of the DataTemplates DataType that is passed in at run-time.

    <DataTemplate DataType="{x:Type local:Controllers}">
        <ListBox ItemsSource="{Binding}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <WrapPanel>
                        <TextBlock Text="{Binding Path=Port}" />
                    </WrapPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </DataTemplate>