XSL
XSL

Reputation: 3055

Why are ListBoxItems added in XAML not styled?

Why are ListBoxItems declared within the XAML itself not affected by the DataTemplate? The template is fine when I bind a source, and that's what I'll be doing ultimately, but just wondering why the declared items aren't styled.

<ListBox>
     <ListBox.ItemTemplate>
         <DataTemplate>
             <Grid>
                 <TextBlock Text="{Binding}" Foreground="Red"/>
             </Grid> 
         </DataTemplate>                   
     </ListBox.ItemTemplate>
     <ListBoxItem>LBI 1</ListBoxItem>
     <ListBoxItem>LBI 2</ListBoxItem>
</ListBox>

Here LBI 1 and LBI 2 are not red but if I was to use ListBox.ItemSource and bind a list, the items are red.

Upvotes: 2

Views: 473

Answers (3)

UIlrvnd
UIlrvnd

Reputation: 786

"When you set an ItemTemplate on an ItemsControl, the UI is generated as follows (using the ListBox as an example):

  1. During content generation, the ItemsPanel initiates a request for the ItemContainerGenerator to create a container for each data item. For ListBox, the container is a ListBoxItem. The generator calls back into the ItemsControl to prepare the container.

  2. Part of the preparation involves the copying of the ItemTemplate of the ListBox to be the ContentTemplate of the ListBoxItem.

  3. Similar to all ContentControl types, the ControlTemplate of a ListBoxItem contains a ContentPresenter. When the template is applied, it creates a ContentPresenter whose ContentTemplate is bound to the ContentTemplate of the ListBoxItem.

  4. Finally, the ContentPresenter applies that ContentTemplate to itself, and that creates the UI."

As you can see above, the datatemplate is used only for newly generated items. Also data templates are generally used to describe/present "the visual structure" of data - your ListBoxItems are already described as ListBoxItems, so they use that template... Hope this makes sense...

Upvotes: 3

Rohit Vats
Rohit Vats

Reputation: 81243

You need to apply Style. DataTemplate is used to apply template to Data which is bound to listBox. Hence not applying to the items which are directly added as child within XAML.

    <ListBox>
        <ListBox.Resources>
            <Style TargetType="ListBoxItem">
                <Setter Property="Foreground" Value="Red"/>
            </Style>
        </ListBox.Resources>
        <ListBoxItem>LBI 1</ListBoxItem>
        <ListBoxItem>LBI 2</ListBoxItem>
    </ListBox>

Upvotes: 2

Joe Brunscheon
Joe Brunscheon

Reputation: 1989

Because LB1 and LB2 as in the example are not part of your data template. When you bind some data to the ItemsSource of your ListBox, those items are displayed according to the data template.

Upvotes: 2

Related Questions