WPF TabControl: Load all tabs at window load
Asked Answered
I

0

13

I have a WPF form with a TabControl containing 2 TabItems. I have validation occuring on controls on one tab that enforce dependent validation of controls on the other tab. However, when the user switches to the second tab, it does not show any the red square around the validated control because the tab contents aren't rendered until that TabItem is viewed for the first time. Is there a way to load the contents of all tabs when the Window is loaded?

Update:

I figured out a way to do this, but it feels very hacky. I added the following code to the MainWindow_OnLoaded event handler in my code behind:

for (var tabIndex = MainTabControl.Items.Count - 1; tabIndex >= 0; tabIndex--)
{
    MainTabControl.SelectedIndex = tabIndex;
    MainTabControl.UpdateLayout();
}

This code simply loops through all tabs in the TabControl and sets them as the active tab and updates the layout. That forces all the contents to initialize. It all happens before the window appears so the user doesn't see the change. I only have 2 tabs in my TabControl, but I could see this being a bit more awkward if there were more tabs.

Initiation answered 19/5, 2015 at 23:43 Comment(4)
For the validation to work correctly when using TabControl you need to wrap the content of each tab in an <AdornerDecorator>Criminate
@Criminate - I've got the <AdornerDecorator> wrapped around my tab content and everything works once I have viewed each tab, but the issue is that the second tab hasn't been viewed yet before validation occurs and when I go to it, I don't have any validation markers.Initiation
It’s a hacky solution if I ever saw one, but here, too, it’s the only way I found to do this. One suggestion, though: you might want to wrap the content of your for loop into a dispatcher call, e.g., Dispatcher.BeginInvoke((Action)(() => { /* your update code */ }));.Byroad
I assume that some logic in the view model is triggered by a "get" of a property. This is a very valid lazy load mechanism. But, if it is a lengthy process , why not activating it at an instantiation of the view model or by another action taking place in the view model layer, disregarding the view ?Laundes

© 2022 - 2024 — McMap. All rights reserved.