Question ListBox.ItemTemplate does not apply to <ListBoxItem>. Why?

StoneCodeMonkey

Well-known member
Joined
Apr 17, 2009
Messages
56
Programming Experience
5-10
I'm trying to understand Item templates and the behavior I am seeing just doesn't make sense.

By the way I have xmlns:sys="clr-namespace:System;assembly=mscorlib" which explains the sys:String below.


In this ListBox, I have a simple ItemTemplate that should change the foreground color on each item. I would have expected this to specifically apply to <ListBoxItem> within the ListBox. However, the template does not apply to the TextBlock or the ListBoxItem.

VB.NET:
            <ListBox>
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <ListBoxItem Foreground="Red" Content="{Binding}"></ListBoxItem>
                    </DataTemplate>
                </ListBox.ItemTemplate>
                <sys:String>1st</sys:String>
                <TextBlock>2nd</TextBlock>
                <ListBoxItem>3rd</ListBoxItem>
                <sys:String>4th</sys:String>
            </ListBox>


In this ListBox, TextBlock and ListBoxItem both clearly support a Foreground property, while sys:String does not.

VB.NET:
            <ListBox>
                <TextBlock Foreground="Red">1st</TextBlock>
                <ListBoxItem Foreground="Blue">2nd</ListBoxItem>
                <sys:String>3rd</sys:String>
            </ListBox>

Why does the ItemTemplate set the Foreground to Red on items that clearly do not have a Foreground property and skip the ones that do?

Regards,
 
ItemTemplate/DataTemplate is mainly for data binding, where template is generated for each bound item. In this case the template is applied to all items except the existing ListBoxItem. That the TextBlock does not inherit the foreground color of the generated ListBoxItem container seems weird. A Style resource may define styles for all ListBoxItems. Relevant articles:
Data Templating Overview
Styling and Templating
 
Back
Top