wpfxamllistboxitemitemcontainerstylecontenttemplate

XAML separate binding of ContainerStyle and ContentTemplate in ListBox


I tried this for a while now and searched in the web without success... Now I dare to ask on stackoverflow myself.

So, the aim is to separate the definitions of the ItemContainerStyle and the ContentTemplate of a ListBoxItem. I have defined the ListBoxItemStyle in a ResourceDictionary and two different DataTemplates in the Window.Resources.

I now like to set the style of the ListBoxItem according to the one defined in the ResourceDictionary and change the DataTemplate with a trigger (IsMouseOver).

My (not working) Code so fare looks like this:

<ListBox HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="20,60,10,10"
         Grid.Row="1" Grid.Column="0"
         PreviewMouseMove="DragMove_PreviewMouseMove"
         PreviewMouseLeftButtonDown="Drag_PreviewMouseLeftButtonDown"
         ItemsSource="{Binding Persons}" VerticalContentAlignment="Center"
         Style="{StaticResource DefaultListBoxStyle}">
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Style" Value="{StaticResource DefaultListBoxItemStyle}"/>
            <Setter Property="ContentTemplate" Value="{StaticResource PersonsListBoxItemTemplate_default}"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="ContentTemplate" Value="{StaticResource PersonsListBoxItemTemplate_infoButtons}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

where DefaultListBoxStyle is the style defined in the ResourceDictionary and PersonsListBoxItemTemplate_default & PersonsListBoxItemTemplate_infoButtons are the DataTemplates defined in the Window.Resources.

Now I get an error, that the style-object must not have an impact on the style-property of the object it belongs to.

I tried different ways, but without success... I also tried to define the style first and then change the template, but it does not work either.

Thank you all for your help!


Solution

  • So you can't set Style Property in Style with Setter. For this you need to use BasedOn:

    <Style TargetType="ListBoxItem" BasedOn="{StaticResource DefaultListBoxItemStyle}">
        <Setter ... />
    </Style>