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);
}
}
這有幫助嗎? http://blogs.msdn.com/b/wpfsdk/archive/2007/10/02/data-validation-in-3-5.aspx – 2010-11-03 12:45:59