Reputation: 329
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.
Upvotes: 0
Views: 1140
Reputation: 329
I was able to change the Background
of the Border
when the item is selected in a ListBox
using a data trigger in the data template.
<DataTemplate DataType="{x:Type model:Topic}" x:Key="TopicNameDataTemplate">
<Grid>
<Border x:Name="Border" ... >
...
</Border>
</Grid>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding Path=IsSelected, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ListBoxItem}}}"
Value="True">
<Setter TargetName="Border" Property="Background" Value="Orange"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
Upvotes: 1