2010-11-03 48 views
0

我有一个文本框用于输入用于指定颜色的十六进制值。我有一个Validator验证字符串是一个有效的十六进制颜色值。以及一个将“FF0000”字符串转换为“#FFFF0000”.NET颜色对象的转换器。我只想在数据有效时转换值,就好像数据无效一样,我会从转换器中得到一个异常。我怎样才能做到这一点?如何仅在输入有效时使用转换器

代码如下仅供参考

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

这有帮助吗? http://blogs.msdn.com/b/wpfsdk/archive/2007/10/02/data-validation-in-3-5.aspx – 2010-11-03 12:45:59

回答

0

您可以使用Binding.DoNothingDependencyProperty.UnsetValue作为转换器中的返回值。

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); 
} 
相关问题