Domanda

Ho una casella di testo per l'immissione di valori esadecimali per specificare il colore. Ho un validatore che convalida che la stringa è un valore esadecimale del colore valido. E un convertitore che converte una stringa come "FF0000" per oggetto "# FFFF0000" NET colore. Voglio valori convertire solo quando i dati sono validi come se i dati non è valido, mi metterò un'eccezione dal convertitore. Come posso fare?

Codice di seguito appena cronaca

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>

Validator

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

Convertitore

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);
    }
}
È stato utile?

Soluzione

È possibile utilizzare Binding.DoNothing o DependencyProperty. UnsetValue come valore di ritorno nel vostro convertitore.

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); 
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top