如何将 WPF 选项卡项标题拉伸到父控件宽度 [英] How to Stretch WPF Tab Item Headers to Parent Control Width

查看:30
本文介绍了如何将 WPF 选项卡项标题拉伸到父控件宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

XAML 中是否有一种方法可以使选项卡项标题跨选项卡控件的宽度延伸?

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.

推荐答案

我借鉴了 Jordan 的例子并对其进行了一些更改.此版本适用于任意数量的标签:

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();
        }
    }
}

xaml 中的相同命名空间:

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>

这篇关于如何将 WPF 选项卡项标题拉伸到父控件宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆