Live Chat Icon For mobile
Live Chat Icon

WPF FAQ - TabControl

Find answers for the most frequently asked questions
Expand All Collapse All

The TabItems have a Visibility property which can be set to Collapsed (no space will be reserved for this tab) or Hidden (not rendered, but space will be reserved for this tab).

        <TabControl x:Name='tabControl1'>
            <TabItem Header='Tab1'></TabItem>
            <TabItem Header='Tab2' Visibility='Hidden'></TabItem>
            <TabItem Header='Tab3' Visibility='Collapsed'></TabItem>
            <TabItem Header='Tab4'></TabItem>

Here is a custom style that changes the look and feel of the tabs (TabItems) in the corresponding window.


<Style TargetType='TabItem'>
  <Setter Property='BorderThickness' Value='3'/>
  <Setter Property='BorderBrush' Value='Red'/>
  <Setter Property='Background' Value='LightBlue'/>
  <Setter Property='VerticalContentAlignment' Value='Center'/>
  <Setter Property='HorizontalContentAlignment' Value='Center'/>
  <Setter Property='Template'>
      <ControlTemplate TargetType='{x:Type TabItem}'>
              <Border CornerRadius='3,3,0,0' Background='{TemplateBinding Background}' 
                   BorderBrush='{TemplateBinding BorderBrush}' 
                   BorderThickness='{TemplateBinding BorderThickness}'/>
            <Border BorderThickness='{TemplateBinding BorderThickness}' 
                 Padding='{TemplateBinding Padding}'>
              <ContentPresenter ContentSource='Header' 
                 HorizontalAlignment='{TemplateBinding HorizontalContentAlignment}' 
                 VerticalAlignment='{TemplateBinding VerticalContentAlignment}'/>

This is how the tabs look with the above style applied on them:


Unfortunately, WPF doesn’t provide a straight forward way of validating a tab page’s content before switching to a new tab, in the first version. One workaround is to listen to the TabItem’s PreviewLostKeyboardFocus event and mark it as Handled as shown below.

        public TabValidation()

            foreach (TabItem item in tabControl1.Items)
                item.PreviewLostKeyboardFocus += new KeyboardFocusChangedEventHandler(item_PreviewLostKeyboardFocus);

        void item_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
            // sender is the TabItem.
            if (this.ValidateTab() == false)
                e.Handled = true;

Share with

Couldn't find the FAQs you're looking for?

Please submit your question and answer.