TextBox is not canceled a second time

When the button is clicked, I check if the value is valid in the TextBox:

txtName.GetBindingExpression(TextBox.TextProperty).UpdateSource();

      

And the text box is highlighted with a red border and a tooltip next to it.

Then I switch to another tab. Go back - TextBox is no longer highlighted. When the button is clicked, I validate again and the validation rule works fine and returns false, but the textbox is still not selected.

How to highlight TextBox as invalid again?

Validation rule:

public class TextRequired : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            var text = value as string;                
            return new ValidationResult(!string.IsNullOrEmpty(text), "Please, enter alue");
        }
    }

      

+3


source to share


1 answer


The validation error advocate (red rectangle) is displayed at the adorner level that belongs to some ancestor to TabControl

. When you switch tabs, the content of the original tab is unloaded, at which point the adorner is removed from that adorner layer, since the adorner and its decorated element are no longer in the same visual tree. However, when you switch back to the original tab, the adorner is not added again. This is a weakness in support for WPF validation proponents. I don't know by design or oversight, but the solution is pretty simple.

Just wrap your tab content in AdornerDecorator

. This will cause the error advertiser to be added to the adorner layer inside the tab, where it will remain even when the tab content is unloaded. When you go back, he will still be there.



<TabItem>
  <AdornerDecorator>
    <!-- tab content -->
  </AdornerDecorator>
</TabItem>

      

+1


source







All Articles