我试图设置SystemColors.HighlightBrushKey总是比所选行的背景暗一点。 因此我使用此代码:
的App.xaml:
<WPFTests2:SelectionBackgroundConverter x:Key="SelectionBackgroundConverter"/>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="{Binding Background, Converter={StaticResource SelectionBackgroundConverter}}"/>
</Application.Resources>
Window1.xaml:
<Window x:Class="WPFTests2.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300" Loaded="Window_Loaded">
<Grid>
<ListBox x:Name="LB" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
</Grid>
Window1.xaml.cs:
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
namespace WPFTests2
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
LB.Items.Add("Text1");
LB.Items.Add("Text2");
LB.Items.Add("Text3");
LB.Items.Add("Text4");
LB.Items.Add("Text5");
}
}
public class SelectionBackgroundConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (value != null)
{
SolidColorBrush brush = (SolidColorBrush)value;
Color newCol = brush.Color;
newCol.R -= 10;
newCol.G -= 10;
newCol.B -= 10;
BrushConverter conv = new BrushConverter();
Brush newBrush = (Brush)conv.ConvertTo(newCol, typeof(Brush));
return newBrush;
}
return Brushes.Transparent;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
//never called
return null;
}
}
}
问题是转换器永远不会被调用... 有没有人知道如何设置所选行的背景比选择它之前的颜色更暗?
感谢任何帮助!
更新
看起来它的工作但遗憾的是并非如此。 我已经纠正了转换器看起来像这样:
public class SelectionBackgroundConverter : IValueConverter
{
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (value != null)
{
SolidColorBrush brush = (SolidColorBrush)value;
Color newCol = brush.Color;
newCol.R -= 10;
newCol.G -= 10;
newCol.B -= 10;
return new SolidColorBrush(newCol);
}
return Brushes.Transparent;
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
// we don't intend this to ever be called
return null;
}
现在的问题是转换器只被调用一次。我的意思是如果我启动程序并单击转换器被调用的任何行。如果我然后单击进入另一行,DataGrid或控制转换器不会被调用。
任何想法如何解决这个问题?
答案 0 :(得分:2)
问题在于此绑定:
Color="{Binding Background, Converter={StaticResource SelectionBackgroundConverter}}"
没有Source
,Background
属性在当前上下文中不存在。将其更改为:
Color="{Binding Source={x:Static SystemColors.HighlightBrush}, Converter={StaticResource SelectionBackgroundConverter}}"
您的转换器将被调用。虽然你的转换器中有bug,但是这应该可以帮助你入门。还要考虑: