我正在寻找一种在 XAML 中修改颜色(SolidColorBrush)的方法。我已经使用 CSS/less 一段时间了 ( less@github ) 并且喜欢它允许我将一种颜色保存为 RGB 并说 darken(@color1, 15%) 的方式获得相同的颜色,但颜色更深一些。
有没有办法在 XAML/C#.Net 中应用此类转换器?类似(伪 xaml)的东西:
<SolidColorBrush x:Key="darkRed"
Color="{StaticResource Red, Converter=Darken}" />
编辑: sa_ddam 的回答几乎就是我所需要的。但是 - 在 ResourceDictionary 中使用它时我无法让它工作。
sa_ddam 的代码有效 - 但以下代码无效:
<Window.Resources>
<cnv:DarkenColorConverter x:Key="Darken" />
<SolidColorBrush x:Key="blue"
Color="Blue" />
<SolidColorBrush x:Key="darkblue"
Color="{Binding Source={StaticResource blue}, Converter={StaticResource Darken}}" />
</Window.Resources>
编辑: 发现我的错误 - 转换器的返回类型必须是 Color,而不是 SolidColorBrush。
请您参考如下方法:
您可以创建一个IValueConverter 来使颜色变深
像这样的东西应该可以解决问题
public class DarkenColorConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
double percentage = 0.8; // Default
if (value is SolidColorBrush)
{
if (parameter != null)
{
double.TryParse(parameter.ToString(), out percentage);
}
Color color = (value as SolidColorBrush).Color;
return new SolidColorBrush(Color.FromRgb((byte)(color.R * percentage), (byte)(color.G * percentage), (byte)(color.B * percentage)));
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotSupportedException();
}
}
这是一个用法示例
<Window x:Class="WpfApplication13.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication13"
Title="MainWindow" x:Name="UI" Width="124" Height="336"
>
<Window.Resources>
<!-- Converter -->
<local:DarkenColorConverter x:Key="Darken" />
<!-- Brush to manipulate -->
<SolidColorBrush x:Key="red" Color="{Binding Source=Red}" />
</Window.Resources>
<StackPanel>
<!-- Original color -->
<Rectangle Fill="{StaticResource red}" Width="100" Height="100" />
<!-- Darken with Converter -->
<Rectangle Fill="{Binding Source={StaticResource red}, Converter={StaticResource Darken}}" Width="100" Height="100"/>
<!-- Using ConverterParameter to select how dark (0.0 - 1.0) -->
<Rectangle Fill="{Binding Source={StaticResource red}, Converter={StaticResource Darken}, ConverterParameter=0.5}" Width="100" Height="100"/>
</StackPanel>
</Window>
结果:
