WPF - Very basic ListBox.ItemTemplate Question

Andy T picture Andy T · Mar 16, 2010 · Viewed 21.5k times · Source

Ok, this is an embarassingly simple-looking problem, but is driving me crazy. I'm learning about DataTemplating and am trying to apply a very VERY simple ItemTemplate to a ListBox.

However, when I run my app, the template is completely ignored and I just get the standard-looking listbox, whereas in fact I'd expect to see a list of checkboxes with 'Test' along side.

I've tried this several times and always the same result. I've checked several resource on Google and all have the same kind of syntax for defining and ItemTemplate on a ListBox, so I really cannot see where I'm going wrong.

Code...

<Grid x:Name="LayoutRoot">
    <ListBox x:Name="TestList"
        SelectionMode="Multiple">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel>
                    <CheckBox Content="Check this checkbox!"/>
                    <TextBlock>Test</TextBlock>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
        <ListBox.Items>
            <ListBoxItem>Bob</ListBoxItem>
            <ListBoxItem>Jim</ListBoxItem>
            <ListBoxItem>Dave</ListBoxItem>
            <ListBoxItem>Larry</ListBoxItem>
            <ListBoxItem>Tom</ListBoxItem>
        </ListBox.Items>            
    </ListBox>
</Grid>

Any help greatly appreciated. Sorry for such a dumb-seeming question, but I've really fallen at the first hurdle here :(

AT

Answer

Jobi Joy picture Jobi Joy · Mar 16, 2010

ItemTemplate wont work when you put ListBoxItem directly as items. General concept is you databind a CRL collection to the ListBox.ItemsSource and then specify the ItemTemplate. Check the below code.

 <Grid x:Name="LayoutRoot">
        <ListBox x:Name="TestList"  SelectionMode="Multiple">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <CheckBox Content="Check this checkbox!"/>
                        <TextBlock Text="{Binding}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
            <ListBox.Items>
                <sys:String>Bob</sys:String>
                <sys:String>Jim</sys:String>
                <sys:String>Dave</sys:String>
                <sys:String>Larry</sys:String>
                <sys:String>Tom</sys:String>
            </ListBox.Items>
        </ListBox>
    </Grid>

where sys is xmlns:sys="clr-namespace:System;assembly=mscorlib"

In this way, there are 5 ListBoxItems getting generated in the background and added to the ListBox.