Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Stretch WPF Tab Item Headers to Parent Control Width

Is there a way in XAML to cause the tab item headers to stretch across the width of the tab control?

For example, I have three tabs: red, blue and green. If I have a tab control with its width set to auto, the tab headers will only fill up part of the space above the tab content, but I want them to fill up all the space. For my three tab example, red should take up the first third of the control, blue should take up the center third, and green the final third.

I have an idea how to do this in a code behind which I am working on now, but I am interested in doing this the easiest way possible.

like image 480
Ben Doerr Avatar asked Apr 01 '09 14:04

Ben Doerr


2 Answers

I took Jordan's example and made some changes to it. This version should work for any number of tabs:

namespace WpfApplication1.Converters {     public class TabSizeConverter : IMultiValueConverter     {         public object Convert(object[] values, Type targetType, object parameter,             System.Globalization.CultureInfo culture)         {             TabControl tabControl = values[0] as TabControl;             double width = tabControl.ActualWidth / tabControl.Items.Count;             //Subtract 1, otherwise we could overflow to two rows.             return (width <= 1) ? 0 : (width - 1);         }          public object[] ConvertBack(object value, Type[] targetTypes, object parameter,             System.Globalization.CultureInfo culture)         {             throw new NotSupportedException();         }     } } 

Same namespace in the xaml:

xmlns:local="clr-namespace:WpfApplication1.Converters" 

And this will make all tabs use it:

<Window.Resources>     <local:TabSizeConverter x:Key="tabSizeConverter" />     <Style TargetType="{x:Type TabItem}">         <Setter Property="Width">             <Setter.Value>                 <MultiBinding Converter="{StaticResource tabSizeConverter}">                     <Binding RelativeSource="{RelativeSource Mode=FindAncestor,             AncestorType={x:Type TabControl}}" />                     <Binding RelativeSource="{RelativeSource Mode=FindAncestor,             AncestorType={x:Type TabControl}}" Path="ActualWidth" />                 </MultiBinding>             </Setter.Value>         </Setter>     </Style> </Window.Resources> 
like image 162
Ryan Versaw Avatar answered Sep 24 '22 10:09

Ryan Versaw


Everyone seems to be going the converter route, but it really is as simple as using a UniformGrid with Rows set to 1 in the TabControl template, in place of the TabPanel. Of course, you will have to re-template it, but this isn't too bad.

like image 43
Charlie Avatar answered Sep 24 '22 10:09

Charlie