Search code examples
silverlighttabcontroltabitem

Silverlight TabControl - Finding and selecting a TabItem from a given Control in the TabItem


I am building a LOB application that has a main section and a TabControl with various TabItems in it. On hitting save the idea is that any fields in error are highlighted and the first field in error gets the focus.

If the first, and only, field in error is on an Unselected tab the tab should then become selected and the field in error should become highlighted and have focus. But I can not get this to work.

What appears to be happening is that the Unselected tab is not in the visual tree so you can't navigate back to the owning TabItem and make it the currently selected TabItem in the TabControl.

Has anyone got an idea on how this can be done\achieved?


Solution

  • How I solved it (by asking the Lead Architect)...

    Create an Interface ITabActivator with one method Activate.

    Create a class derived from Grid and ITabActivator called TabPageActivator. The constructor of which takes the TabITem and the TabControl.

    Instead of adding a simple Grid to the TabItem.Contents add a TabPageActivator.

    Change the Parent detection to use...

    DependencyObject parent = _Control.Parent;

    ...instead of using the VisualTreeHelper.

    So when you navigate the Hierarchy test for...

    if ( parent is TabActivator ) (parent as ITabActivator).Activate( )

    ... so when Activate is called

    m_TabControl.SelectedItem = m_TabItem; // From Constructor Parameters.

    ...and don't forget you may have nested tabs so you need to keep going up the Hierarchy.