Created
March 26, 2013 16:10
-
-
Save wendazhou/5246681 to your computer and use it in GitHub Desktop.
A simple helper to manually toggle WPF validation on FrameworkElements.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Provides helpers to manually toggle validation errors. | |
/// </summary> | |
public static class ManualValidation | |
{ | |
// this dummy attached property is used as a source | |
// of the binding. | |
static readonly DependencyProperty DummyProperty = | |
DependencyProperty.RegisterAttached("DummyProperty", typeof(object), typeof(ManualValidation), new PropertyMetadata(null)); | |
// this class implements a dummy validation rule without behaviour. | |
private class DummyValidationRule : ValidationRule | |
{ | |
public override ValidationResult Validate(object value, CultureInfo cultureInfo) | |
{ | |
throw new NotImplementedException(); | |
} | |
} | |
/// <summary> | |
/// Manually mark a validation error on the given framework element. | |
/// </summary> | |
/// <param name="element">The instance of <see cref="FrameworkElement"/> on which to mark the validation error.</param> | |
/// <param name="errorContent">An object representing the content of the error.</param> | |
public static void MarkInvalid(FrameworkElement element, object errorContent) | |
{ | |
// create a dummy binding. Conveniently, we bind to the tag of the FrameworkElement, | |
// so as to minimise the potential interaction with other code. | |
var binding = new Binding("Tag") {Source = element, Mode = BindingMode.OneWayToSource}; | |
// set the binding on to our dummy property. | |
BindingOperations.SetBinding(element, DummyProperty, binding); | |
// we now get the live binding expression. | |
var bindingExpression = element.GetBindingExpression(DummyProperty); | |
// create a dummy binding error, with the specified error content. | |
var validationError = new ValidationError(new DummyValidationRule(), binding, errorContent, null); | |
// and manually set the validation error on the binding. | |
Validation.MarkInvalid(bindingExpression, validationError); | |
} | |
/// <summary> | |
/// Clears all manually assigned errors on the given <paramref name="element"/>. | |
/// </summary> | |
/// <param name="element">The instance of <see cref="FrameworkElement"/> on which to clear the validation.</param> | |
public static void ClearValidation(FrameworkElement element) | |
{ | |
// to clear an error, we simply remove all bindings to our dummy property. | |
BindingOperations.ClearBinding(element, DummyProperty); | |
} | |
} |
Very useful, thank you !
Useful even after 9 years. Thank you very much!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It worked like a charm! Thank you very much!!