ListBoxItem IsSelected Style

I still do not understand. Could you show me how to override the default behavior in a ListBox. Each time a ListBoxItem is selected, the background of the border must be changed. Not the background of the entire line, but only the background of the border that is indicated.

 <ListBox ItemsSource="{Binding Source={StaticResource AssetsViewSource}}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Border BorderThickness="2" BorderBrush="Black">
                    <StackPanel>
                        <TextBlock Text="Name: " />
                        <TextBlock Text="{Binding Name}" />
                    </StackPanel>
                </Border>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
+3
source share
2 answers

Use the DataTemplate trigger collection with RelativeSource to get you to the containing ListBoxItem:

<DataTemplate>
  <Border BorderThickness="2" BorderBrush="Black" Name="Bd">
    <StackPanel>
      <TextBlock Text="Name: " />
      <TextBlock Text="{Binding Name}" />
    </StackPanel>
  </Border>
  <DataTemplate.Triggers>
    <DataTrigger Value="True"
                 Binding="{Binding 
                              IsSelected, 
                              RelativeSource={RelativeSource 
                                  AncestorType={x:Type ListBoxItem}}}">
      <!-- everybody loves HotPink -->
      <Setter TargetName="Bd" Property="Background" Value="HotPink"/>  
    </DataTrigger>
  </DataTemplate.Triggers>
</DataTemplate>
+10
source

Just add the following to the ListBox list item tag

<ListBox.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
</ListBox.Resources>

That should do the trick.

+2
source

Source: https://habr.com/ru/post/1740077/


All Articles