I am using a tab control to group different input fields like text boxes. I am validating the user input of those text boxes via IDataErrorInfo
in my view model.
Now, when the user input is not valid and I change the tab pages back and forth the validation indicator disappears from the text box.
I found a possible solution, that the validation must be forced on tab page change. This is working somehow because the validation logic in the VM is executed but the visual indicator on the text box is still not there.
I already tried updating source and target of the binding and putting the update logic into a Dispatcher.BeginInvoke
block with background priority in order to give the UI the chance to render completely. But nothing of that worked. Has anybody an idea which part I am missing out?
My code looks as follows:
the xaml markup
<TabControl SelectionChanged="TabControl_SelectionChanged"
<!-- more tab pages -->
<TabItem Header="Tab 2">
<Grid>
<TextBox Text="{Binding TextProperty, ValidatesOnDataErrors=True}" />
</Grid>
</TabItem>
</TabControl>
the code behind
private static IEnumerable<DependencyObject> FindVisualChildren(object obj)
{
// traverses the visual tree recursively and returns all visual children of obj
}
private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (!(e.Source is TabControl tabControl))
{
return;
}
foreach (TabItem tab in tabControl.Items)
{
if (!tab.IsSelected)
{
continue;
}
// Re-validate the controls within the selected tab
foreach (var child in FindVisualChildren(tab.Content))
{
if (child is TextBox textBox)
{
var binding = textBox.GetBindingExpression(TextBox.TextProperty);
binding?.UpdateSource();
}
}
}
}