Pregunta

Tengo un cuadro de texto para introducir valores hexadecimales para especificar el color. Tengo un validador que tiene que la cadena es un valor de color hexadecimal válido. Y un convertidor que convierte una cadena como "FF0000" al objeto "# FFFF0000" .NET color. Quiero valores de convertir sólo cuando los datos son válidos como si los datos no es válida, conseguiré una excepción desde el convertidor. ¿Cómo puedo hacer eso?

código de abajo lo digo

XAML

<TextBox x:Name="Background" Canvas.Left="328" Canvas.Top="33" Height="23" Width="60">
    <TextBox.Text>
        <Binding Path="Background">
            <Binding.ValidationRules>
                <validators:ColorValidator Property="Background" />
            </Binding.ValidationRules>
            <Binding.Converter>
                <converters:ColorConverter />
            </Binding.Converter>
        </Binding>
    </TextBox.Text>
</TextBox>

Validador

class ColorValidator : ValidationRule
{
    public string Property { get; set; }

    public ColorValidator()
    {
        Property = "Color";
    }

    public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
    {
        string entry = (string)value;
        Regex regex = new Regex(@"[0-9a-fA-F]{6}");
        if (!regex.IsMatch(entry)) {
            return new ValidationResult(false, string.Format("{0} should be a 6 character hexadecimal color value. Eg. FF0000 for red", Property));
        }
        return new ValidationResult(true, "");
    }
}

convertidor de

class ColorConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string entry = ((Color)value).ToString();
        return entry.Substring(3); 
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string entry = (string)value;
        return (Color)System.Windows.Media.ColorConverter.ConvertFromString("#FF" + entry);
    }
}
¿Fue útil?

Solución

Se puede usar Binding.DoNothing o DependencyProperty. UnsetValue como valor de retorno en su convertidor.

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
    string entry = (string)value;
    Regex regex = new Regex(@"[0-9a-fA-F]{6}");
    if (!regex.IsMatch(entry)) {
        return Binding.DoNothing;

    return entry.Substring(3); 
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top