كيفية استخدام المحول فقط عندما يكون الإدخال صالحًا

StackOverflow https://stackoverflow.com/questions/4087036

سؤال

لدي مربع نص لإدخال قيم سداسية عشرية لتحديد اللون. لديّ مدقق يتحقق من صحة أن السلسلة عبارة عن قيمة ملونة سداسية صالحة. ومحول يحول سلسلة مثل "FF0000" إلى "#FFFF0000" .NET COLOR. أرغب في تحويل القيم فقط عندما تكون البيانات صالحة كما لو كانت البيانات غير صالحة ، سأحصل على استثناء من المحول. كيف أقوم بذلك؟

الكود أدناه فقط لمعلوماتك

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>

المدقق

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

محول

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);
    }
}
هل كانت مفيدة؟

المحلول

يمكنك استخدام binding.donothing أو الاعتماد كقيمة الإرجاع في المحول الخاص بك.

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); 
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top