How to Stretch WPF Tab Item Headers to Parent Control Width

后端 未结 11 1947
花落未央
花落未央 2020-11-29 23:17

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

11条回答
  •  遥遥无期
    2020-11-29 23:54

    In addition to Ryan Versaw's accepted solution which gives equal tabItem header widths, I found the following way to make it dependent on the length of each header.

    First we get the string of each tabItem header by adding this line to the xaml multibinding. Thus it becomes:

    
               
               
               
    
    

    And a bit more of code in the Converter (values[] gets also the tabItem Header):

    public object Convert(object[] values, Type targetType, object parameter,
            System.Globalization.CultureInfo culture)
        {
            TabControl tabControl = values[0] as TabControl;
    
            string AllHeaders = "";
            for (int i = 0; i < tabControl.Items.Count; i++)
            {
                int index = tabControl.Items[i].ToString().IndexOf("Header:") + "Header:".Length;
                string currentHeader = tabControl.Items[i].ToString().Substring(index);
                currentHeader = currentHeader.Substring(0, currentHeader.Length - " Content:".Length);
                AllHeaders += currentHeader;
            }
    
            //Normalize width according to header length
            double width = values[2].ToString().Length * tabControl.ActualWidth / AllHeaders.Length;
    
            //Subtract 1, otherwise we could overflow to two rows.
            var retVal = (width <= 1) ? 0 : (width - 1);
            return retVal;
        }
    

    I suspect there might be a more efficient way to get the AllHeaders string of all the headers, but it works fine as it is ...

提交回复
热议问题