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

11

19

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

PSEUDO-CODE:

((TabItem)(MainTabControl.Children[0])).SetFocus();
Barrier answered 4/8, 2009 at 12:11 Comment(0)
A
35

How about this?

MainTabControl.SelectedIndex = 0;
Afterdeck answered 4/8, 2009 at 12:15 Comment(2)
In my case, as I use a datagrid, something locks the selection or the focus, so I needed to wrap this into a call to Dispatcher.Legere
This answer does NOT set the focus, only the selection.Selle
U
13
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.

Unsex answered 20/2, 2013 at 15:38 Comment(1)
This answer applies to WinForms, not WPF which the OP has specified in his tags.Selle
H
5

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.

Haitian answered 23/6, 2011 at 3:46 Comment(0)
H
3

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;
Huron answered 16/7, 2014 at 12:1 Comment(0)
K
2
tabControl1.SelectedTab = item;
item.Focus();
Killigrew answered 4/8, 2009 at 12:16 Comment(2)
What is the benefit of using item.Focus() after setting the selected Item?Raver
@HugoEstrada Focus and selection are not the same thing. Create a couple triggers based off of each of these properties to see what I mean. Or see my related question: https://mcmap.net/q/665173/-visual-indication-of-last-focused-item-when-application-loses-focus-alternative-to-iskeyboardfocuswithin/2596334Selle
S
2

Basically all of the answers here deal with SELECTION, which does not answer the question.
Maybe that is what OP wanted, but the question very specifically asks for FOCUS.

TabItem item = (TabItem)MainTabControl.Items[0];
// OR
TabItem item = (TabItem)MainTabControl.SelectedItem;
// Then
item.Focus();
Selle answered 3/10, 2019 at 12:8 Comment(6)
This appears to be the only sensible answer, BUT: my Items[] collection does not contain instances of TabITem, (that would make too much sense,) it contains viewmodels, because I am using ItemsSource="{Binding... and SelectedItem="{Binding... -- do you have a solution in this case?Cistern
@MikeNakis did you ever find a solution to your question? I asked what you were looking for here: https://mcmap.net/q/665174/-how-to-focus-on-a-newly-added-tabitem-of-a-wpf-tabcontrol/1306012Tendance
@BrunoBieri no, I did not. I looked at your question, but I still do not have an answer.Cistern
@MikeNakis Have you considered basing your "viewmodels" classes on UIElement or ContentElement? So long as one of those is in the base of the custom class you are using as a ViewModel, it should have the Focus method and events.Selle
@ScottSolmer that sounds like a horrible, horrible, horrible beyond words idea.Cistern
@MikeNakis I don't disagree. However that is the result of choosing "ViewModel" as the type for TabControl Items. That is a horrible idea.Selle
T
1

tabControl.SelectedItem = tabControl.Items[0];

Tungstic answered 4/8, 2009 at 12:19 Comment(0)
C
1

If you have a Tabcontroller named tabControl you could set the selectedIndex from different methods, i use following methods mostly.

codebehind:

tabControl.SelectedIndex = 0; // Sets the focus to first tabpanel

clientside:

First, put the following javascript in your aspx/ascx file:

<script type="text/javascript">
function SetActiveTab(tabControl, activeTabIndex) {
    var activeTab = tabControl.GetTab(activeTabIndex);
    if(activeTab != null)
        tabControl.SetActiveTab(activeTab);
}</script>

Then add following clientside event to prefered controller:

OnClientClick="function(s, e) { SetActiveTab(tabControl, 0);
Concent answered 4/8, 2009 at 12:50 Comment(1)
The question relates to WPF, however your answer is ASP.NET specific.Haitian
C
1

it's better to use the following type of code to select the particular item in the particular tab...

.

 private void PutFocusOnControl(Control element)
        {
            if (element != null)
                Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Input,
                    (System.Threading.ThreadStart)delegate
                    {
                        element.Focus();
                    });
        }

And in calling time... tabcontrol.isselected=true; PutFocusOnControl(textbox1);

will works fine...

Coolie answered 23/5, 2012 at 13:16 Comment(0)
S
0

Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged 'MsgBox(TabControl1.SelectedIndex)

    If TabControl1.SelectedIndex = 0 Then
        txt_apclntFrstName.Select()
    Else
        txtApplcnNo.Select()
    End If


End Sub
Shamblin answered 26/3, 2013 at 8:30 Comment(0)
P
0

It worked for me to set focus to the last tab just after I open it:

//this is my assignment of the collection to the tab control
DictTabControl.DataContext = appTabs.DictTabs;  

//set the selected item to the last in the collection, i.e., the one I just added to the end.
DictTabControl.SelectedItem = DictTabControl.Items[(DictTabControl.Items.Count-1)];
Pyramid answered 24/8, 2021 at 21:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.