C# 更改列表框项目的选择颜色
我有一个普通的C# 更改列表框项目的选择颜色,c#,wpf,xaml,checkbox,listbox,C#,Wpf,Xaml,Checkbox,Listbox,我有一个普通的列表框,我想将选择颜色更改为红色。这是我到目前为止得到的 <Style x:Key="myLBStyle" TargetType="{x:Type ListBoxItem}"> <Style.Resources> <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="red" />
列表框
,我想将选择颜色更改为红色。这是我到目前为止得到的
<Style x:Key="myLBStyle" TargetType="{x:Type ListBoxItem}">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="red" />
<SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}"
Color="red" />
</Style.Resources>
</Style>
它起作用了。SelectedItem为红色,即使不对焦也保持红色
这是我真正的问题:在我的网格中,我也有一个复选框
,我希望只有选中复选框时才能应用上述样式
因此,如果选中该复选框,我希望选择颜色为红色,如果未选中该复选框,则选择颜色为蓝色(或默认颜色)
我浏览了web,找不到任何东西,所以我正在寻求帮助。您需要在代码中处理和事件,因为我不相信您可以使用XAML中的
触发器添加或删除资源。但是,它们是只读的,因此也不能直接设置它们
我找到了一种方法,但它涉及从user32.dll
导入kkk
方法,因此它可能不适用于假心肠。有关更多信息,请参阅pinvoke.net网站上的页面。从链接页面:
[DllImport("user32.dll", SetLastError=true)]
public static extern bool SetSysColors(int cElements, int [] lpaElements, int [] lpaRgbValues);
public const int COLOR_DESKTOP = 1;
//example color
System.Drawing.Color sampleColor = System.Drawing.Color.Lime;
//array of elements to change
int[] elements = {COLOR_DESKTOP};
//array of corresponding colors
int[] colors = {System.Drawing.ColorTranslator.ToWin32(sampleColor)};
//set the desktop color using p/invoke
SetSysColors(elements.Length, elements, colors);
//save value in registry so that it will persist
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Control Panel\\Colors", true);
key.SetValue(@"Background", string.Format("{0} {1} {2}", sampleColor.R, sampleColor.G, sampleColor.B));
您可以有两种不同的样式-
所有setter和触发器的默认样式
空白样式,其中定义了资源,并将此样式设置为基于默认样式的
样式,以便从默认样式继承所有设置器和触发器
然后,您可以根据复选框选中的状态交换ItemContainerStyle
样本:
<StackPanel>
<StackPanel.Resources>
<Style x:Key="myLBStyleDefault">
<!-- All setters and triggers go here -->
</Style>
<Style x:Key="myLBStyleWithRed"
BasedOn="{StaticResource myLBBaseStyle}"
TargetType="{x:Type ListBoxItem}">
<Style.Resources>
<SolidColorBrush
x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="Red" />
<SolidColorBrush
x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}"
Color="Red" />
</Style.Resources>
</Style>
</StackPanel.Resources>
<CheckBox x:Name="chk"/>
<ListBox>
<ListBox.Style>
<Style TargetType="ListBox">
<Setter Property="ItemContainerStyle"
Value="{StaticResource myLBStyleDefault}"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsChecked, ElementName=chk}"
Value="True">
<Setter Property="ItemContainerStyle"
Value="{StaticResource myLBStyleWithRed}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</ListBox.Style>
</ListBox>
</StackPanel>