2013-03-02 86 views
1

我正在尋找一種在XAML中修改顏色(SolidColorBrush's)的方法。我一直在使用CSS/less一段時間([email protected]),就像它允許我將一種顏色保存爲RGB,並說darken(@color1, 15%)以獲得相同的着色,但有點暗。XAML中的資源轉換

有沒有辦法在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

回答

4

您可以創建一個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> 

結果的一個例子:

enter image description here

+0

感謝您的幫助 - 這幾乎是我所需要的。我已經修改了我的上述問題以提供一些細節。 – dhh 2013-03-02 17:34:35