Search code examples
wpflistboxdatatemplate

How to change part of the datatemplate background


I have a ListBox, its DateTemplate like this:

<Grid Margin="30,0,0,0" HorizontalAlignment="Left">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition />
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                <Image Source="{Binding Path=IconSource}"/>
                <TextBlock Grid.Column="1" Background="{x:Null}" Text="{Binding Path=DisplayText, Mode=Default}" Foreground="Black"/>
            </Grid>

and this is the ItemContainerStyle:

 <Style x:Key="Test" TargetType="ListBoxItem">
        <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBoxItem">
                    <Border Name="Border" SnapsToDevicePixels="True">
                        <ContentPresenter/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsSelected" Value="true">
                            <Setter TargetName="Border" Property="Background" Value="Blue" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

When one ListBoxItem is selected, is it possible not to set the image's background? Like in Intellisense of VS, the icon of the API doens't have background.


Solution

  • The simplest thing is to put your image inside another Grid, and set the Grid's Background to the background color you would like the image to have - then when you change the Background of the parent Border, the image's parent grid will protect it from the background color change.