moggizx moggizx - 1 month ago 8
C# Question

Disabling/overriding highlighting on WPF controls

I have a RichTextBox with ScrollViewer.VerticalScrollBarVisibility=Auto, and this is working just like I want it to. However, when I hover my mouse over the document I get a blue border around the entire RichTextBox element and the only way I can seem to make it go away is by setting IsHitTestVisible=false, but if I do that the scroll bar becomes disabled too... Other things I've tried is IsFocusable=false and making a trigger for the RichTextBox's style, without any success:

<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="BorderBrush" Value="{x:Null}"/>
</Trigger>
</Style.Triggers>


I have the same problem with images in my application that are displayed in a ListBox. I have a ListBox looking like this:

<ListBox ItemsSource="{Binding Photos}"
BorderBrush="{x:Null}"
SelectedItem="{Binding SelectedPhoto, Mode=TwoWay}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid IsItemsHost="True"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Columns="3" Rows="1"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Image Source="{Binding}"
Stretch="Uniform"
SnapsToDevicePixels="True"/>
</DataTemplate>
</ListBox.ItemTemplate>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="Transparent"/>
</Style.Resources>
<Setter Property="Foreground" Value="Transparent"/>
<Setter Property="BorderBrush" Value="{StaticResource Brush_Secondary}"/>
<Setter Property="BorderThickness" Value="5"/>
<Setter Property="Margin" Value="5"/>
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="BorderBrush" Value="{StaticResource Brush_Primary}"/>
</Trigger>
<Trigger Property="IsSelected" Value="True">
<Setter Property="BorderBrush" Value="{StaticResource Brush_Selected}"/>
</Trigger>
</Style.Triggers>
</Style>
</ListBox.ItemContainerStyle>
</ListBox>


But no matter which colors I use (Brush_Primary/Secondary/Selected) the border is always just different shades of blue... How do I get rid of this blue overlay/highlight thing that seems to exist for every single WPF control?

Answer

You can override the RichTextBox template to remove the default value -

<Style TargetType="RichTextBox">
   <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate>
                <Border x:Name="Bd"
                        BorderBrush="{TemplateBinding BorderBrush}" 
                        BorderThickness="{TemplateBinding BorderThickness}"
                        SnapsToDevicePixels="True"
                        Background="{TemplateBinding Background}">
                    <ScrollViewer Name="PART_ContentHost"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>