I have a listbox with some items. When an item is selected, I want to change the background color of the UserControlButton.
How can I do this?
<Window.Resources>
<Style x:Key="ListBoxItemStyle" TargetType="{x:Type ListBoxItem}">
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
</Style>
</Window.Resources>
<Border x:Name="UserScrollContainer">
<ListBox x:Name="UserContainer" ItemsSource="{Binding allUserViewModel.Users}"
Background="Transparent"
HorizontalContentAlignment="Stretch"
ScrollViewer.HorizontalScrollBarVisibility="Hidden"
ScrollViewer.VerticalScrollBarVisibility="Visible"
BorderThickness="0" Margin="0" Padding="0"
ItemContainerStyle="{DynamicResource ListBoxItemStyle}">
<ListBox.ItemTemplate>
<DataTemplate>
<local:UserControlButton x:Name="UserControlButton" />
// Change background color depending if it is selected
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Border>
EDIT
I know I can add something like this:
<Style x:Key="ListBoxItemStyle" TargetType="{x:Type ListBoxItem}">
<Setter Property="FocusVisualStyle" Value="{x:Null}"/>
<Setter Property="Background" Value="Lightblue"/>
<Style.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter Property="Background" Value="Red"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Background" Value="Yellow"/>
</Trigger>
</Style.Triggers>
</Style>
but then I get this result:
I need to change the background of the usercontrol, not of the listboxitem.
You have several approaches to solve your problem. One of them I will describe here.
You can define <Style />
on your <UserContorl />
, in order to reflect the ListBoxItem.IsSelected
property:
<DataTemplate>
<local:UserControlButton x:Name="UserControlButton">
<local:UserControlButton.Style>
<Style TargetType="{x:Type local:UserControlButton}">
<Setter Property="Background" Value="Lightblue"/>
<Style.Triggers>
<DataTrigger Binding="{Binding Path=IsSelected, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListBoxItem}}" Value="true">
<Setter Property="Background" Value="Red"/>
</DataTrigger>
</Style.Triggers>
</Style>
</local:UserControlButton.Style>
</local:UserControlButton>
</DataTemplate>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments