Ali
Ali

Reputation: 3666

Adding image on top of ListBoxItem in WPF

I have a ListBox with some ListBoxItems. Each ListBoxItem contains some text and a background image. When the user clicks a ListBoxItem I want to add an image on top of the ListBoxItem (it decorates the item with some additional looks).

I'm looking for a way to overlay the image onto the clicked ListBoxItem. That's the code I have so far:

    <ListBox Margin="0,34,0,25.113" Background="{x:Null}" BorderThickness="0">
        <ListBoxItem Content="First Item" Height="71.96" Margin="0,10,0,0">
            <ListBoxItem.Background>
                <ImageBrush ImageSource="Untitled-4.png"/>
            </ListBoxItem.Background>
        </ListBoxItem>
    </ListBox>

Upvotes: 2

Views: 1458

Answers (1)

Rachel
Rachel

Reputation: 132548

Put your ListBoxItem.Content in a panel which allows overlapping controls, such as a Grid, and make your top image's Visibililty be based on ListBoxItem.IsSelected

<ListBox.Resources>
    <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
</ListBox.Resources>

<ListBoxItem Height="71.96" Margin="0,10,0,0">
    <ListBoxItem.Background>
        <ImageBrush ImageSource="Untitled-4.png"/>
    </ListBoxItem.Background>
    <Grid>
        <TextBlock Text="First Item" 
                   VerticalAlignment="Center" HorizontalAlignment="Center" />

        <Image Source="SomeImage.jpg"
               Visibility="{Binding IsSelected, 
                   RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}, 
                   Converter={StaticResource BooleanToVisibilityConverter}}" />
    </Grid>
</ListBoxItem>

Edit

You can also remove the blue background for the SelectedItem by overwritting the HighlightBrush Color and making it Transparent

<ListBox.Resources>
    <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />

    <Style TargetType="{x:Type ListBoxItem}">
        <Style.Resources>
            <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
            <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent" />
        </Style.Resources>
    </Style>
</ListBox.Resources>

Upvotes: 2

Related Questions