【发布时间】:2010-11-06 16:53:57
【问题描述】:
我试图将 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 或控件,则不会调用转换器。
知道如何解决这个问题吗?
【问题讨论】:
标签: wpf background selection converter