I have a custom ValidationRule that requires access to the ViewModel in order to validate a supplied value in conjunction with other properties of the ViewModel. I previously tr
I know this is an old questions but I was in the same situation as the initial poster maintaining an existing application and didn't want to rewrite it totally and I ended up finding a way around this that works at least in my situation.
I was trying to validate a value placed into a text box by the user, but didn't want to commit the value back to the model if the value was not valid. However in order to validate I needed to access other properties of the DataContext object to know if the input was valid or not.
What I ended up doing was creating a property on the validator class that I had created that holds an object of the type that the datacontext should be. In that handler I added this code:
TextBox tb = sender as TextBox;
if (tb != null && tb.DataContext is FilterVM)
{
try
{
BindingExpression be = tb.GetBindingExpression(TextBox.TextProperty);
Validator v = be.ParentBinding.ValidationRules[0] as Validator;
v.myFilter = tb.DataContext as FilterVM;
}
catch { }
}
This code basically uses the textbox that got the focus, gets it's binding and finds the validator class that is it's first (and only) ValidationRule. Then I have a handle on the class and can just set it's property to the DataContext of the textbox. Since this is done when the textbox first gets focus it is setting the value before any user input can be done. When the user inputs some value, then, the property is already set and can be used in the validator class.
I did put in the following in my validator class just in case it ever gets there without the property being correctly set:
if (myFilter == null)
{ return new ValidationResult(false, "Error getting filter for validation, please contact program creators."); }
However that validation error has never come up.
Kind of hack-ish but it works for my situation and doesn't require a full re-write of the validation system.