I am trying to validate in my WPF application using the solution in WPF Validation Error Detection .
public static bool IsValid(DependencyObject parent) { // Validate all the bindings on the parent bool valid = true; LocalValueEnumerator localValues = parent.GetLocalValueEnumerator(); while (localValues.MoveNext()) { LocalValueEntry entry = localValues.Current; if (BindingOperations.IsDataBound(parent, entry.Property)) { Binding binding = BindingOperations.GetBinding(parent, entry.Property); foreach (ValidationRule rule in binding.ValidationRules) { ValidationResult result = rule.Validate(parent.GetValue(entry.Property), null); if (!result.IsValid) { BindingExpression expression = BindingOperations.GetBindingExpression(parent, entry.Property); System.Windows.Controls.Validation.MarkInvalid(expression, new ValidationError(rule, expression, result.ErrorContent, null)); valid = false; } } } } // Validate all the bindings on the children for (int i = 0; i != VisualTreeHelper.GetChildrenCount(parent); ++i) { DependencyObject child = VisualTreeHelper.GetChild(parent, i); if (!IsValid(child)) { valid = false; } } return valid; }
The problem I am facing is that when I look at the code for the TextBox, I do not get the Text property. The only properties I get are "PageHeight", "Instance" and "UndoManagerInstance". Therefore, I cannot check the rules for binding in a TextBox.
Does anyone have any ideas why I will not get the right properties? Is there any other way to force controls in WPF? I could not find anyone else who had this problem.
Update: The text fields I'm trying to check are within the DataTemplate. I found that if I copy one of the TextBoxes and put it right in the window, I can get the data. Using Woodstock, I saw that the data source for TextBoxes in the template is “ParentTemplate”, but it is “Local” for the TextBox outside the template.
So the question is, how can I get DependencyProperties for controls inside a DataTemplate?
source share