wpf 如何在 XAML 中将颜色转换为画笔?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3309709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:57:17  来源:igfitidea点击:

How do I convert a Color to a Brush in XAML?

wpfdata-bindingxamlcolorsconverter

提问by dthrasher

I want to convert a System.Windows.Media.Color value to a System.Windows.Media.Brush. The color value is databound to a Rectangle object's Fill property. The Fill property takes a Brush object, so I need an IValueConverter object to perform the conversion.

我想将 System.Windows.Media.Color 值转换为 System.Windows.Media.Brush。颜色值数据绑定到 Rectangle 对象的 Fill 属性。Fill 属性采用 Brush 对象,因此我需要一个 IValueConverter 对象来执行转换。

Is there a built-in converter in WPF or do I need to create my own? How do I go about creating my own if it becomes necessary?

WPF 中是否有内置转换器,还是我需要创建自己的转换器?如果有必要,我该如何创建自己的?

回答by Jens

I know I am really late to the party, but you don't need a converter for this.

我知道我参加聚会真的很晚,但是您不需要为此使用转换器。

You could do

你可以做

<Rectangle>
    <Rectangle.Fill>
        <SolidColorBrush Color="{Binding YourColorProperty}" />
    </Rectangle.Fill>
</Rectangle>

回答by HCL

It seems that you have to create your own converter. Here a simple example to start:

看来您必须创建自己的转换器。这是一个简单的例子:

public class ColorToSolidColorBrushValueConverter : IValueConverter {

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
        if (null == value) {
            return null;
        }
        // For a more sophisticated converter, check also the targetType and react accordingly..
        if (value is Color) {
            Color color = (Color)value;
            return new SolidColorBrush(color);
        }
        // You can support here more source types if you wish
        // For the example I throw an exception

        Type type = value.GetType();
        throw new InvalidOperationException("Unsupported type ["+type.Name+"]");            
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
        // If necessary, here you can convert back. Check if which brush it is (if its one),
        // get its Color-value and return it.

        throw new NotImplementedException();
    }
}

To use it, declare it in the resource-section.

要使用它,请在资源部分中声明它。

<local:ColorToSolidColorBrushValueConverter  x:Key="ColorToSolidColorBrush_ValueConverter"/>

And the use it in the binding as a static resource:

并在绑定中将其用作静态资源:

Fill="{Binding Path=xyz,Converter={StaticResource ColorToSolidColorBrush_ValueConverter}}"

I have not tested it. Make a comment if its not working.

我没有测试过。如果它不起作用,请发表评论。

回答by Kylo Ren

A Converteris not needed here. You can define a Brushin XAMLand use it. It would be better to define the Brushas a Resourceso it can be used other places required.

Converter这里不需要A。您可以定义一个BrushinXAML并使用它。最好将Brusha定义为 aResource以便它可以用于其他需要的地方。

XAMLis as below:

XAML如下:

<Window.Resources>
    <SolidColorBrush Color="{Binding ColorProperty}" x:Key="ColorBrush" />
</Window.Resources>
<Rectangle Width="200" Height="200" Fill="{StaticResource ColorBrush}" />

回答by Hymanson Pope

I wanted to do this HCL's way rather than Jens' way because I have a lot of things bound to the Color, so there's less duplication and boiler-plate .Fillnodes.

我想用 HCL 的方式而不是 Jens 的方式来做这个,因为我有很多东西绑定到Color,所以重复和样板.Fill节点更少。

However when trying to write it, ReSharper pointed me to the WPF Toolkit's implementation of the ColorToSolidColorBrushConverter. You need to include the following namespace declaration in the main Window/UserControl node:

但是,在尝试编写它时,ReSharper 向我指出了WPF Toolkit对 ColorToSolidColorBrushConverter 的实现。您需要在主 Window/UserControl 节点中包含以下命名空间声明:

xmlns:Toolkit="clr-namespace:Microsoft.Windows.Controls.Core.Converters;assembly=WPFToolkit.Extended"

Then a static resource in the Window/UserControl resources:

然后是Window/UserControl资源中的一个静态资源:

<Toolkit:ColorToSolidColorBrushConverter x:Key="colorToSolidColorBrushConverter" />

Then you can do it like HCL's answer:

然后你可以像 HCL 的回答那样做:

<Rectangle Fill="{Binding Color, Converter={StaticResource colorToSolidColorBrushConverter}}" />

回答by G.Y

With some more enhancment to HCL answer, I tested it - it works.

通过对 HCL 答案的更多增强,我对其进行了测试 - 它有效。

public class ColorToSolidColorBrushValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
            return null;

        if (value is Color)
            return new SolidColorBrush((Color)value);

        throw new InvalidOperationException("Unsupported type [" + value.GetType().Name + "], ColorToSolidColorBrushValueConverter.Convert()");
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null)
            return null;

        if (value is SolidColorBrush)
            return ((SolidColorBrush)value).Color;

        throw new InvalidOperationException("Unsupported type [" + value.GetType().Name + "], ColorToSolidColorBrushValueConverter.ConvertBack()");
    }

}

回答by Stacked

Converter:

转换器:

[ValueConversion(typeof(SolidColorBrush), typeof(Color))]
public class SolidBrushToColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (!(value is SolidColorBrush)) return null;
        var result = (SolidColorBrush)value;
        return result.Color;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

XAML:

XAML:

//...
<converters:SolidBrushToColorConverter x:Key="SolidToColorConverter" />
//...
<Color>
    <Binding Source="{StaticResource YourSolidColorBrush}"
             Converter="{StaticResource SolidToColorConverter}">
    </Binding>
</Color>
//...

回答by Norman

In addition to HCLs answer: If you don't want to care if System.Windows.Media.Color is used or System.Drawing.Color you can use this converter, which accepts both:

除了 HCL 答案:如果您不想关心是否使用 System.Windows.Media.Color 或 System.Drawing.Color 您可以使用此转换器,它接受两者:

public class ColorToSolidColorBrushValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        switch (value)
        {
            case null:
                return null;
            case System.Windows.Media.Color color:
                return new SolidColorBrush(color);
            case System.Drawing.Color sdColor:
                return new SolidColorBrush(System.Windows.Media.Color.FromArgb(sdColor.A, sdColor.R, sdColor.G, sdColor.B));
        }

        Type type = value.GetType();
        throw new InvalidOperationException("Unsupported type [" + type.Name + "]");
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}