Silverlight, TabControl: How to set tab focus programmatically from user controls

Photobucket

For some reason, when we built an silverlight app, we didn't use the navigation and page controls. Instead, we have a single page with a border. This border swaps what would have been pages, which are controls containing tab controls. These tab controls themselves contain other user controls. Everything has worked out fine until now, when the need to link between these tabs arose.

The problem: I need to have a link from one tab content that will take me to another one. The tab content is itself another user control.

The solution:

I rejected traversing the tree because I thought it was fragile. Adding one border can break the code. Instead I created an App public member. May not be the prettiest solution, but it sure is the shortest that works.

The steps:
1. Go to App.xaml.cs, and add your new member

    public partial class App : Application
    {
        public TabControl MainPageTab;  // New member type TabControl for which we need to set TabItem focus 
   ....

2. In your user control, add the code that will set focus on the target TabItem in the Button_Click() method

        private void ToHome_Click(object sender, RoutedEventArgs e)
        {
            var app = (App)App.Current;                                                                  //get the current app
            var home = (TabItem)app.MainPageTab.FindName("tabHome");  // get the target TabItem
 
            app.MainPageTab.SelectedItem = home;                                     // Set focus via setting SelectedItem
        }

Again, using page controls may be a better practice, but this technique is useful in scenarios where apps were built without using pages, and you need to navigate through tabs. It gets the job done in a more robust manner than navigating the control tree would have done.