开发者

How to only use Converter when input is valid

开发者 https://www.devze.com 2023-01-23 02:04 出处:网络
I have a text box for entering hex values for specifying color. I have a Validator that validates that the string is a valid hex color value. And a converter that converts a string like \"FF0000\" to

I have a text box for entering hex values for specifying color. I have a Validator that validates that the string is a valid hex color value. And a converter that converts a string like "FF0000" to "#FFFF0000" .NET color object. I want to only convert values when the data is valid as if data is invalid, I will get an exception from the converter. How can I do that?

Code below just 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));
       开发者_Python百科 }
        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);
    }
}


You can use Binding.DoNothing or DependencyProperty.UnsetValue as the return value in your converter.

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

精彩评论

暂无评论...
验证码 换一张
取 消