Переопределить фон SelectedItem в ListBox - PullRequest
0 голосов
/ 06 июня 2018

Я знаю, что на эту тему отвечали снова и снова, но я не могу добиться ее реализации.

Я бы хотел изменить способ отображения моих ListboxItem при выборе (иесли возможно, избавьтесь от этой отвратительной границы выделения).

На нескольких постах здесь и на MSDN я обнаружил, что способ добиться этого - переопределить следующие кисти в ItemContainerStyle:

  • HighlightBrushKey
  • ControlBrushKey
  • HighlightTextBrushKey
  • InactiveSelectionHighlightBrushKey

Я пробовал несколько способовдостичь этого, но это систематически терпит неудачу.Обновление устарело это поведение или я его неправильно внедряю?

Вот мой код:

<ListBox BorderBrush="Transparent" ItemsSource="{Binding MyItemSource}" SelectedItem="{Binding SelectedItem, Mode=TwoWay}" SelectionMode="Single">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>                                
                <Label HorizontalAlignment="Center" Margin="0 1 0 0" Foreground="Black" FontSize="14" Content="{Binding Name}"/>
            </Grid>
        </DataTemplate>      
    </ListBox.ItemTemplate>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="{Binding ColumnCount}"/> 
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Style.Resources>
                <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Blue"/>
                <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Green"/>
                <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Red"/>
                <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="Yellow" />
            </Style.Resources>
        </Style>
    </ListBox.ItemContainerStyle>
</ListBox>

1 Ответ

0 голосов
/ 07 июня 2018

Хорошо, так что я наконец-то смог переопределить эти кисти.Похоже, что кисти SystemColor больше не используются.

Я переопределил фон SelectedItem, определив его (большая часть кода взята из Blend для VS, шаблон для переопределения - General Item Container).

Вот ItemContainerStyle, который я использовал:

<Style x:Key="FocusVisual">
        <Setter Property="Control.Template">
            <Setter.Value>
                <ControlTemplate>
                    <Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="1" StrokeDashArray="1 2"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <SolidColorBrush x:Key="Item.MouseOver.Background" Color="#1F26A0DA"/>
    <SolidColorBrush x:Key="Item.MouseOver.Border" Color="#a826A0Da"/>
    <SolidColorBrush x:Key="Item.SelectedInactive.Background" Color="#3DDADADA"/>
    <SolidColorBrush x:Key="Item.SelectedInactive.Border" Color="#FFDADADA"/>
    <SolidColorBrush x:Key="Item.SelectedActive.Background" Color="Gray"/>
    <SolidColorBrush x:Key="Item.SelectedActive.Border" Color="Gray"/>
    <Style x:Key="ListBoxItemStyle1" TargetType="{x:Type ListBoxItem}">
        <Setter Property="SnapsToDevicePixels" Value="True"/>
        <Setter Property="Padding" Value="0"/>
        <Setter Property="HorizontalContentAlignment" Value="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
        <Setter Property="VerticalContentAlignment" Value="{Binding VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="BorderBrush" Value="Transparent"/>
        <Setter Property="BorderThickness" Value="1"/>
        <Setter Property="FocusVisualStyle" Value="{StaticResource FocusVisual}"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ListBoxItem}">
                    <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true">
                        <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                    </Border>
                    <ControlTemplate.Triggers>
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <Condition Property="IsMouseOver" Value="True"/>
                            </MultiTrigger.Conditions>
                            <Setter Property="Background" TargetName="Bd" Value="{StaticResource Item.MouseOver.Background}"/>
                            <Setter Property="BorderBrush" TargetName="Bd" Value="{StaticResource Item.MouseOver.Border}"/>
                        </MultiTrigger>
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <Condition Property="Selector.IsSelectionActive" Value="False"/>
                                <Condition Property="IsSelected" Value="True"/>
                            </MultiTrigger.Conditions>
                            <Setter Property="Background" TargetName="Bd" Value="{StaticResource Item.SelectedInactive.Background}"/>
                            <Setter Property="BorderBrush" TargetName="Bd" Value="{StaticResource Item.SelectedInactive.Border}"/>
                        </MultiTrigger>
                        <MultiTrigger>
                            <MultiTrigger.Conditions>
                                <Condition Property="Selector.IsSelectionActive" Value="True"/>
                                <Condition Property="IsSelected" Value="True"/>
                            </MultiTrigger.Conditions>
                            <Setter Property="Background" TargetName="Bd" Value="{StaticResource Item.SelectedActive.Background}"/>
                            <Setter Property="BorderBrush" TargetName="Bd" Value="{StaticResource Item.SelectedActive.Border}"/>
                        </MultiTrigger>
                        <Trigger Property="IsEnabled" Value="False">
                            <Setter Property="TextElement.Foreground" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

Кстати, как переопределить этот шаблон, используя Blend: на панели «Объекты и временная шкала»: щелкните правой кнопкой мыши на вашем ListBox> Редактировать дополнительные шаблоны> Редактировать контейнер общего элемента (ItemContainerStyle)

...