¿Cómo convierto un Color en un Pincel en XAML?


Quiero convertir un Sistema.Windows.Medio.Valor de color a un Sistema.Windows.Medio.Cepillo. El valor de color está enlazado a la propiedad Fill de un objeto Rectángulo. La propiedad Fill toma un objeto Brush, por lo que necesito un objeto IValueConverter para realizar la conversión.

¿Hay un convertidor incorporado en WPF o necesito crear el mío propio? ¿Cómo puedo crear el mío propio si es necesario?

Author: dthrasher, 2010-07-22

7 answers

Parece que tienes que crear tu propio convertidor. Aquí un ejemplo simple para comenzar:

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();
    }
}

Para usarlo, declararlo en la sección de recursos.

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

Y el uso en el enlace como un recurso estático:

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

No lo he probado. Haz un comentario si no funciona.

 57
Author: HCL,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-23 10:16:03

Sé que llego muy tarde a la fiesta, pero no necesitas un convertidor para esto.

Usted podría hacer

<Rectangle>
    <Rectangle.Fill>
        <SolidColorBrush Color="{Binding YourColorProperty}" />
    </Rectangle.Fill>
</Rectangle>
 125
Author: Jens,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-15 12:04:37

Quería hacer esta HCL a la manera en lugar de la manera de Jens porque tengo un montón de cosas vinculadas a la Color, por lo que hay menos duplicación y nodos de placa de caldera .Fill.

Sin embargo, al intentar escribirlo, ReSharper me señaló a la implementación del ColorToSolidColorBrushConverter del WPF Toolkit. Debe incluir la siguiente declaración de espacio de nombres en el nodo Ventana principal/UserControl:

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

Luego un recurso estático en la ventana / UserControl recursos:

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

Entonces puedes hacerlo como la respuesta de HCL:

<Rectangle Fill="{Binding Color, Converter={StaticResource colorToSolidColorBrushConverter}}" />
 6
Author: Jackson Pope,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-12 18:29:41

Con un poco más de mejora a la respuesta HCL, lo probé - funciona.

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()");
    }

}
 3
Author: G.Y,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-24 15:49:59

A Converter no se necesita aquí. Puede definir un Brush en XAML y usarlo. Sería mejor definir el Brush como un Resource para que pueda ser utilizado otros lugares requeridos.

XAML es como abajo:

<Window.Resources>
    <SolidColorBrush Color="{Binding ColorProperty}" x:Key="ColorBrush" />
</Window.Resources>
<Rectangle Width="200" Height="200" Fill="{StaticResource ColorBrush}" />
 3
Author: Kylo Ren,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-17 16:43:05

Convertidor:

[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:

//...
<converters:SolidBrushToColorConverter x:Key="SolidToColorConverter" />
//...
<Color>
    <Binding Source="{StaticResource YourSolidColorBrush}"
             Converter="{StaticResource SolidToColorConverter}">
    </Binding>
</Color>
//...
 1
Author: Stacked,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-10-24 00:04:18

Además de HCLs respuesta: Si usted no quiere cuidar si el sistema.Windows.Medio.Se utiliza color o Sistema.Dibujo.Color puede utilizar este convertidor, que acepta ambos:

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();
    }
} 
 0
Author: Norman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-29 07:31:54