How can I make a specific TabItem gain focus on a TabControl without click event?

46,762

Solution 1

How about this?

MainTabControl.SelectedIndex = 0;

Solution 2

this.tabControl1.SelectedTab = this.tabControl1.TabPages["tSummary"];

I've found it's usually a best practice to name your tabs and access it via the name so that if/when other people (or you) add to or subtact tabs as part of updating, you don't have to go through your code and find and fix all those "hard coded" indexes. hope this helps.

Solution 3

I realise this was answered a long time ago, however a better solution would be to bind your items to a collection in your model and expose a property that selected item is bound to.

XAML:

<!-- MyTemplateForItem represents your template -->
<TabControl ItemsSource="{Binding MyCollectionOfItems}"
            SelectedItem="{Binding SelectedItem}"
            ContentTemplate="{StaticResource MyTemplateForItem}">
</TabControl>

Code Behind:

public ObservableCollection<MyItem> MyCollectionOfItems {
    get;
    private set;
}

private MyItem selectedItem;
public MyItem SelectedItem{
    get { return selectedItem; }
    set {
        if (!Object.Equals(selectedItem, value)) {
            selectedItem = value;
            // Ensure you implement System.ComponentModel.INotifyPropertyChanged
            OnNotifyPropertyChanged("SelectedItem");
        }
    }
}

Now, all you have to do to set the item is:

MyItem = someItemToSelect;

You can use the same logic with the SelectedIndex property, further, you can use the two at the same time.

This approach allows you to separate your model correctly from the UI, which could allow you to replace the TabControl with something else down the line but not requiring you to change your underlying model.

Solution 4

Look at the properties for the tab control... Expand the TabPages properties "collection"... Make note of the names you gave the members.

ie. a tab control called tabMain with 2 tabs called tabHeader and tabDetail

Then to select either tab...You have to set it with the tabname

tabMain.SelectedTab = tabHeader;

Solution 5

tabControl1.SelectedTab = item;
item.Focus();
Share:
46,762
Angry Dan
Author by

Angry Dan

web/software developer, .NET, C#, WPF, PHP, software trainer, English teacher, have philosophy degree, love languages, run marathons my tweets: http://www.twitter.com/edward_tanguay my runs: http://www.tanguay.info/run my code: http://www.tanguay.info/web my publications: PHP 5.3 training video (8 hours, video2brain) my projects: http://www.tanguay.info

Updated on July 09, 2022

Comments

  • Angry Dan
    Angry Dan almost 2 years

    How can I tell my TabControl to set the focus to its first TabItem, something like this:

    PSEUDO-CODE:

    ((TabItem)(MainTabControl.Children[0])).SetFocus();