WPF设置ListBoxItem失去焦点时的背景色不生效的问题

探讨了在WPF中,ListBoxItem选中项在失去焦点后如何保持背景色不变的问题。介绍了通过自定义样式资源及.NET版本适配解决此问题的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

默认情况下,当选中的ListBoxItem失去焦点的时候,其背景色变为白色;而通常情况下,我们希望其失去焦点时候背景色仍然为蓝色,网上查了下资料,说是通过如下代码可以解决:

<Style TargetType="ListBoxItem">
	<Style.Resources>
		<!--SelectedItem with focus-->
		<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="#3399FF"/>
		<SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="White"/>
		<!--SelectedItem without focus-->
		<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="#3399FF"/>
		<SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}" Color="White"/>
	</Style.Resources>
</Style>

可我加入到项目中并没有效果,后来在StackOverflow上查到,原来是.Net版本问题,在.Net4.5之前的版本是可以的,.Net4.5之后的版本还需要在程序启动时候设置如下代码:

FrameworkCompatibilityPreferences.AreInactiveSelectionHighlightBrushKeysSupported = false;

原文地址

 

在 C# WPF设置 `ListBoxItem` 的样式可以通过多种方式实现,具体取决于应用场景和需求。以下是几种常见方法及其使用场景。 ### 通过 XAML 定义静态样式 可以直接在 XAML 文件中定义 `ListBoxItem` 的样式,并将其应用到特定的 `ListBox` 控件上: ```xml <ListBox> <ListBox.ItemContainerStyle> <Style TargetType="{x:Type ListBoxItem}"> <Setter Property="Background" Value="LightBlue"/> <Setter Property="Foreground" Value="DarkRed"/> <Setter Property="FontSize" Value="14"/> </Style> </ListBox.ItemContainerStyle> </ListBox> ``` 上述代码将所有 `ListBoxItem` 的背景设为浅蓝色、前景文字颜色设为深红色,并调整字体大小为 14。 ### 动态绑定样式 如果需要动态地为每个 `ListBoxItem` 设置不同的样式,可以结合数据绑定实现。首先定义一个类来存储样式信息: ```csharp public class ItemStyleInfo { public Brush Background { get; set; } public string Content { get; set; } } ``` 然后在 XAML 中绑定该对象: ```xml <ListBox ItemsSource="{Binding Items}"> <ListBox.ItemTemplate> <DataTemplate> <ListBoxItem Background="{Binding Background}" Content="{Binding Content}"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox> ``` 这种方法适用于根据数据源动态改变项的外观。 ### 在代码中动态设置样式 对于需要在运行动态创建并设置样式的场景,可以在 C# 代码中创建 `ListBoxItem` 并指定其样式: ```csharp private void CreateStyledItems() { var listBox = new ListBox(); var item = new ListBoxItem { Content = "示例项", Style = (Style)FindResource("CustomListBoxItemStyle") }; listBox.Items.Add(item); } ``` 这里的 `CustomListBoxItemStyle` 是在资源中预先定义好的样式[^3]。 ### 自定义 ControlTemplate 为了更精细地控制 `ListBoxItem` 的外观,可以通过自定义 `ControlTemplate` 实现。以下是一个简单的模板定义: ```xml <ControlTemplate x:Key="CustomListBoxItemTemplate" TargetType="{x:Type ListBoxItem}"> <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"> <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/> </Border> </ControlTemplate> ``` 应用此模板到 `ListBoxItem` 上即可看到效果[^5]。 ---
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值