How to change ListBox selection background color?
You must override the Drawitem
event and set the DrawMode
property to DrawMode.OwnerDrawFixed
check this sample
private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index<0) return;
//if the item state is selected them change the back color
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
e = new DrawItemEventArgs(e.Graphics,
e.Font,
e.Bounds,
e.Index,
e.State ^ DrawItemState.Selected,
e.ForeColor,
Color.Yellow);//Choose the color
// Draw the background of the ListBox control for each item.
e.DrawBackground();
// Draw the current item text
e.Graphics.DrawString(listBox1.Items[e.Index].ToString(),e.Font, Brushes.Black, e.Bounds, StringFormat.GenericDefault);
// If the ListBox has focus, draw a focus rectangle around the selected item.
e.DrawFocusRectangle();
}
Change background color for selected ListBox item
You need to use ListBox.ItemContainerStyle.
ListBox.ItemTemplate specifies how the content of an item should be displayed. But WPF still wraps each item in a ListBoxItem control, which by default gets its Background set to the system highlight colour if it is selected. You can't stop WPF creating the ListBoxItem controls, but you can style them -- in your case, to set the Background to always be Transparent or Black or whatever -- and to do so, you use ItemContainerStyle.
juFo's answer shows one possible implementation, by "hijacking" the system background brush resource within the context of the item style; another, perhaps more idiomatic technique is to use a Setter
for the Background property.
Changing WPF Listbox SelectedItem text color and highlight/background Color using C#
Solution:
<Window x:Class="ListBoxStyle.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:ListBoxStyle"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<Style x:Key="_ListBoxItemStyle" TargetType="ListBoxItem">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<Border Name="_Border"
Padding="2"
SnapsToDevicePixels="true">
<ContentPresenter />
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="true">
<Setter TargetName="_Border" Property="Background" Value="Yellow"/>
<Setter Property="Foreground" Value="Red"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<ListBox ItemContainerStyle="{DynamicResource _ListBoxItemStyle}"
Width="200" Height="250"
ScrollViewer.VerticalScrollBarVisibility="Auto"
ScrollViewer.HorizontalScrollBarVisibility="Auto">
<ListBoxItem>Hello</ListBoxItem>
<ListBoxItem>Hi</ListBoxItem>
</ListBox>
</Grid>
</Window>
How to change ListBox selected items' background color in Asp.Net
First up I'd use classes instead of defining the colours in your code (it's just easier to change in the future).
Edit:
You're asking to change the way the UI behaves, you could potentially confuse the user. As far as I know there's no way to override those default gray and blue styles that are applied to selected items. If you must go that way then you need to look at some sort of custom control.
This'll be in the region of what you want so you can apply full customisation to it: reinventing a drop-down with css and jquery/
or Custom SelectBox
Change Selection Color of ListBoxItem in WPF
Both approaches do not work because:
- The default control templates may not necessarily use the system colors.
- The default control template triggers take precedence over your style setters.
You have to extract the default style and control template e.g. by using Visual Studio or Blend in order to have a working base to start from. Adapt the colors in the styles an control template triggers.
<SolidColorBrush x:Key="Item.MouseOver.Background"
Color="#1F26A0DA" />
<SolidColorBrush x:Key="Item.MouseOver.Border"
Color="#a826A0Da" />
<SolidColorBrush x:Key="Item.SelectedActive.Background"
Color="#3D26A0DA" />
<SolidColorBrush x:Key="Item.SelectedActive.Border"
Color="#FF26A0DA" />
<SolidColorBrush x:Key="Item.SelectedInactive.Background"
Color="#3DDADADA" />
<SolidColorBrush x:Key="Item.SelectedInactive.Border"
Color="#FFDADADA" />
<Style x:Key="FocusVisual">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<Rectangle Margin="2"
StrokeDashArray="1 2"
SnapsToDevicePixels="true"
StrokeThickness="1"
Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style x:Key="ListBoxItemStyle"
TargetType="{x:Type ListBoxItem}">
<Setter Property="SnapsToDevicePixels"
Value="True" />
<Setter Property="Padding"
Value="4,1" />
<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"
Background="{TemplateBinding Background}"
BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
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>
Then use the style in your ListBox
by explicitly referencing it or make it an implicit style style by omitting the x:Key
, so it will be applied to all ListBoxItem
s in scope.
<ListBox ItemContainerStyle="{StaticResource ListBoxItemStyle}">
Change ListBox Item Background color programmatically
Here you go:
foreach (var object1 in objects1)
{
Thread.Sleep(1);
listBox1.Items.Add(new ListBoxItem { Content = object1.label, Background = Brushes.Blue });
}
foreach (var object2 in objects2)
{
Thread.Sleep(1);
ListBox2.Items.Add(new ListBoxItem { Content = objects2.label, Background = Brushes.Red });
//I want these Objects to be red
}
A better way would be to use data binding, styles, etc.
How to change the background color of a ListBox Item when hovering?
As the ListBox does not provide the MouseEnterItem and MouseHoverItem Events, it is necessary to code this functionality yourself, tracking the coordinates of the mouse to determine which item the mouse is over.
The following question is very similar, aimed at showing a tooltip for each item when hovered over. Michael Lang's answer is a very good workaround and should be adaptable for your purposes:
How can I set different Tooltip text for each item in a listbox?
Change background color of selected item in listbox
how to change the background color of selected item in listbox
I think you want to change the definition of your ItemContainerStyle
. Try something like this:
<ListBox ItemContainerStyle="{StaticResource ListBoxItemStyle1}" ...
The resource "ListBoxItemStyle1" should contain the control template for ListBoxItem
:
<Style TargetType="ListBoxItem" x:Name="ListBoxItemStyle1">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="ListBoxItem">
<!-- template here -->
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
The control template in turn defines the "Selected" visual state. From the page you linked, "ListBoxItemStyle1" defines that visual state as follows (yellow background):
<VisualState x:Name="Selected">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Background" Storyboard.TargetName="InnerGrid">
<DiscreteObjectKeyFrame KeyTime="0" Value="Yellow"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Foreground" Storyboard.TargetName="ContentPresenter">
<DiscreteObjectKeyFrame KeyTime="0" Value="Green"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
Note that, by default, the ListBoxItem's "selected" state uses as its background the user's current "accent brush", as seen below. This is probably the source of the dark violet color that you see. (You can find all default styles and templates in the Windows Phone SDK folder.)
<VisualState x:Name="Selected">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentContainer" Storyboard.TargetProperty="Foreground">
<DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PhoneAccentBrush}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
You can modify this as needed -- copy-paste a default style, either from the Windows SDK, or from the linked page, and set the background and other properties to whatever you want.
For more background info on control templates and visual states, see Customizing the Appearance of an Existing Control by Using a ControlTemplate.
Related Topics
How to Pass Properties as "Out" or "Ref" Parameters
Excel Interop: _Worksheet or Worksheet
Get Instance of Excel Application with C# by Handle
Threadpool Not Starting New Thread Instantly
How to Get Around Lack of Covariance with Ireadonlydictionary
64 Bit C# with a 32 Bit Vb6 Com Object
Formatting Datetime in ASP.NET Core 3.0 Using System.Text.JSON
C# - Static Types Cannot Be Used as Type Arguments
How Do Events Cause Memory Leaks in C# and How Do Weak References Help Mitigate That
How to Initialize a Datetime Field
Why Cannot I Cast My Com Object to the Interface It Implements in C#