I’m trying to make ValidationRule which depends on some property from (for example) data model.
I have TextBox with validator which have to know about the model object “Scheme”. I’ve tryed to add Scheme into Resources but this didn’t work. And after I’ve found some solution relying on dependency properties.
According to this http://dedjo.blogspot.com/2007/05/fully-binded-validation-by-using.html I’ve made:
/// <summary>
/// Check text value for emptiness and uniqueness
/// </summary>
public class EmptyAndUnique : ValidationRule
{
public UniqueChecker UniqueChecker { get; set; }
public string ErrorMessage { get; set; }
public override ValidationResult Validate(object value,
CultureInfo cultureInfo)
{
string inputString = (value).ToString();
var result = new ValidationResult(true, null);
// Check uniqueness
if(this.UniqueChecker.Scheme.Factors.Any(f => f.Uid == inputString))
{
result = new ValidationResult(false, this.ErrorMessage);
return result;
}
// Check emptiness
if (inputString.Trim().Equals(string.Empty))
{
result = new ValidationResult(false, this.ErrorMessage);
return result;
}
return result;
}
}
/// <summary>
/// Wrapper for DependencyProperty. (trick)
/// </summary>
public class UniqueChecker : DependencyObject
{
public static readonly DependencyProperty SchemeProperty =
DependencyProperty.Register("Scheme", typeof(Scheme),
typeof(UniqueChecker), new FrameworkPropertyMetadata(null));
public Scheme Scheme
{
get { return (Scheme)GetValue(SchemeProperty); }
set { SetValue(SchemeProperty, value); }
}
}
This does not work either.
1) According to article:
Scheme="{Binding ElementName=expressionFactorEditorWindow, Path=Scheme}"
this does not work because:
cos our dependency object is not part
of logical tree, so you can not use
ElementName or DataContext as source
for internal data binding.
But why it’s not part of logical tree?
2) How can I bind properties of my ValidationRule to some dynamic resources
UPDATE
While watching for better solution I made this:
- Add Event which checks uniqueness into ValidationRule
- Add Handler into Window class
- Raise event from ValidationRule and check result from EventArgs
What are you binding to that you are trying to add Validation for. How I usually handle this by having the object I am binding to implement IDataErrorInfo. Then I can put my error handling in that object and have access to anything I need. This would be possible if you are in control of the object you are Binding to.