這是一個很大棘手的代碼隱藏的事。基本上,你可以設置代碼的臨時綁定,並提出驗證錯誤,當輸入有效的值,你可以再次刪除所有的臨時綁定的東西。
我這裏用的是什麼,我認爲一個不好的做法(但它是從什麼好):現在
/// <summary>
/// Marks a textBox control as invalid (via validation error) from code.
/// </summary>
/// <param name="textBox">The text box.</param>
/// <param name="errorContent">Content of the error.</param>
public static void ValidationMarkInvalid(TextBox textBox, String errorContent)
{
DependencyProperty textProp = TextBox.TextProperty;
if (!BindingOperations.IsDataBound(textBox, textProp))
{
if (textBox.DataContext == null)
{
textBox.DataContext = new EmptyDataContext();
}
Binding b = new Binding("CodeBehind");
b.FallbackValue = textBox.Text;
b.ValidatesOnExceptions = true;
BindingOperations.SetBinding(textBox, textProp, b);
}
BindingExpression bindingInError =
textBox.GetBindingExpression(TextBox.TextProperty);
var validationError = new ValidationError(
new EmptyValidationRule(),
bindingInError,
errorContent,
new Exception(errorContent));
Validation.MarkInvalid(bindingInError, validationError);
}
/// <summary>
/// Clears the validation error from a textBox.
/// </summary>
/// <param name="textBox">The text box.</param>
public static void ValidationClear(TextBox textBox)
{
DependencyProperty textProp = TextBox.TextProperty;
if (BindingOperations.IsDataBound(textBox, textProp))
{
String value = textBox.Text;
Validation.ClearInvalid(textBox.GetBindingExpression(TextBox.TextProperty));
BindingOperations.ClearBinding(textBox, textProp);
textBox.Text = value;
EmptyDataContext ctx = textBox.DataContext as EmptyDataContext;
if (ctx != null)
{
textBox.DataContext = null;
}
}
}
#region Nested Type: EmptyDataContext
private sealed class EmptyDataContext : INotifyPropertyChanged
{
public Object CodeBehind
{
get
{
throw new FormatException();
}
set
{
throw new FormatException();
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
#endregion
#region Nested Type: EmptyValidationRule
private sealed class EmptyValidationRule : ValidationRule
{
/// <summary>
/// When overridden in a derived class, performs validation checks on a value.
/// </summary>
/// <param name="value">The value from the binding target to check.</param>
/// <param name="cultureInfo">The culture to use in this rule.</param>
/// <returns>
/// A <see cref="T:System.Windows.Controls.ValidationResult"/> object.
/// </returns>
public override ValidationResult Validate(Object value, CultureInfo cultureInfo)
{
return new ValidationResult(false, String.Empty);
}
}
#endregion
,從代碼隱藏你這樣做:
ValidationMarkInvalid(textBox, "Please enter something valid!");
,並清除驗證:
ValidationClear(textBox);
PS:如果你不想驗證例外,你可以從上面的方法中刪除EmptyDataContext類。
是的,我想我會一直做的代碼我自己。我認爲微軟的想法集中於綁定是好的,但由於這個目的而限制驗證的方式並不是那麼好。謝謝盧卡斯。 – Carlo 2009-09-28 17:12:18
@卡羅:完全同意。 – Kredns 2009-09-28 21:08:44
嗨。這個主題有什麼更新嗎?我也想這樣做。 – 2015-08-07 13:49:44