简体   繁体   中英

Changing TabControl SelectedIndex when adding a new TabItem

I made a button to add a new TabItem in my TabControl. It works fine, but i would like the SelectedIndex to be on the new TabItem when i add a new one. The code of the

private void AddNewTabItem(object sender, MouseButtonEventArgs e)
    {
        ...
        tabControl.Items.Add(tabItem);
        tabControl.SelectedIndex = tabControl.Items.Count - 1;
    }

But this doesnt work, because the new TabItem is created after all the function linked to my button click are executed. So, when i change the SelectedIndex, the new TabItem is not created yet.

I searched for a triggerEvent on the TabControl class, like "WhenItemsChange" but i found nothing.

Thanks for help, and sorry if this is not clear.

You may create TabItems that are selected by default.

In case ti is already a TabItem, just write

ti.IsSelected = true;
tabControl.Items.Add(ti);

If not, assign an appropriate Style to the TabControl's ItemContainerStyle :

<TabControl x:Name="tabControl">
    <TabControl.ItemContainerStyle>
        <Style TargetType="TabItem">
            <Setter Property="IsSelected" Value="True"/>
        </Style>
    </TabControl.ItemContainerStyle>
</TabControl>

Try this:

private void AddNewTabItem(object sender, MouseButtonEventArgs e)
{
    ...
    tabControl.Items.Add(ti);
    Dispatcher?.BeginInvoke((Action)(
            () => tabControl.SelectedIndex = tabControl.Items.Count - 1));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM