I have a ListBox with an ItemTemplateSelector. All the data templates returned by the template selector have a Border. I'd like to change the border's background color when the mouse is over it. To achieve this, I added to the listbox a ListBoxItem control template with a trigger for IsMouseOver but I have no idea how to reference the data template's Border from the trigger's setter. My best bet was the following setter but it had no effect:
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Border.Background" Value="Yellow" />
</Trigger>
Is there a way to do this in XAML, or perhaps to drill down the visual tree in code to find the Border somehow?
I'd also like to change the Border's background color when the item is selected in the ListBox. I know that I could change Foreground
with a ListBoxItem
style like the following:
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Foreground" Value="Red"/>
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
but unlike Foreground
, Background
is not inherited, so the Border
in the DataTemplate
will not receive the trigger's brush.
DataTemplate
the question is whether it should affect anything within the template in the first place. It's not something one would commonly do. If theDataTemplate
should respond to selection it might make sense to also put that logic inside thatDataTemplate
in the first place. – H.B.Border
(returned by theDataTemplate
) of the selected item instead of the default background color change painted byListBoxItem
. I realized the control template cannot access the visual tree of theContent
. Instead, I could use a style (see updated post) if theBackground
property was inherited. As it is not inherited, I still haven't found a solution. – Drew