Frage

ich ein Textfeld haben Hex-Werte für die Eingabe für Farbe angeben. Ich habe einen Validator, der bestätigt, dass die Zeichenfolge ein gültiger Hex-Farbwert ist. Und ein Konverter, der wandelt eine Zeichenkette wie „FF0000“ bis „# FFFF0000“ .NET Farbobjekt. Ich möchte nur convert Werte, wenn die Daten gültig ist, als ob Daten ungültig ist, werde ich eine Ausnahme von dem Wandler erhalten. Wie kann ich das tun?

-Code unten nur FYI

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

Converter

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);
    }
}
War es hilfreich?

Lösung

Sie können mit Binding.DoNothing oder DependencyProperty. UnsetValue als Rückgabewert im Konverter.

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); 
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top