Reputation: 1995
How do I get a databound ListBox to accept a templated Style (from within my ResourceDictionary with the same name as the respective Style) for the ListBoxItem?
I see in Blend 4 that within the SimpleStyles ResourceDictionary file that the "SimpleListBoxItem" has property set to:
d:IsControlPart="True"
but I am only able to use this when explicitly using the SimpleListBoxItem Style for xaml hard-coded ListBoxItems?
What makes sense to me is to apply the style to the ControlTemplate within the ListBox. I see the Control template within the listbox looks like:
ControlTemplate TargetType="{x:Type ListBox}">
<Grid>
<Border x:Name="Border" BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
Background="{TemplateBinding Background}"
/>
<ScrollViewer Margin="1" Style="{DynamicResource SimpleScrollViewer}" Focusable="false" Background="{TemplateBinding Background}">
<!-- The StackPanel is used to display the children by setting IsItemsHost to be True -->
<StackPanel Margin="2" IsItemsHost="true"/>
</ScrollViewer>
</Grid>
Is there a way to put one more nested "ItemsHost" Style template within that stackpanel? Maybe a DataTemplate?
Thanks in advance, let me know if further clarification is needed!
Upvotes: 1
Views: 2776
Reputation: 102793
There are two options for applying a style to the items from within the ListBox
style, ItemContainerStyle
and ItemTemplate
.
1) ItemContainerStyle
applies to the type ListBoxItem
-- setting it styles the container of each item in the list:
<Style TargetType="ListBoxItem" x:Key="SimpleListBoxItem">
<Setter Property="Background" Value="Green">
<!-- etc -->
</Style>
<Style TargetType="ListBox" x:Key="ListBoxStyle">
<Setter Property="ItemContainerStyle" Value="{StaticResource SimpleListBoxItem}">
</Style>
2) The ItemTemplate
property allows you to complete redefine the template for how each item is displayed, eg:
<Style TargetType="ListBox" x:Key="ListBoxStyle">
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBlock Text="This is an item" />
<ContentControl Grid.Column="1" Text="{Binding}" />
<Grid>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
Upvotes: 3