如何使TabControl.Itemtemplate(TextBlock)占据全部可用宽度

时间:2019-08-19 13:25:40

标签: c# wpf

我希望TabControl(文本块)占据窗口中可用的全部宽度。应该在三个选项卡(页眉,SOP和变量)之间分配相等数量的可用空间。

<TabControl Name="Tabct" Height="auto" Width="auto" HorizontalAlignment="Stretch">
    <TabControl.Resources>
        <DataTemplate DataType="{x:Type local:Header}">
            <local:HeaderUserControl />
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:SOP}">
            <local:SOPUserControl />
        </DataTemplate>
        <DataTemplate DataType="{x:Type local:Variable}">
            <local:VariableUserControl />
        </DataTemplate>
    </TabControl.Resources>
    <TabControl.ItemTemplate>
        <DataTemplate DataType="{x:Type local:ITab}">
            <TextBlock HorizontalAlignment="Stretch">
                <Run Text="{Binding HeaderName}" />
            </TextBlock>
        </DataTemplate>
    </TabControl.ItemTemplate>
</TabControl>

1 个答案:

答案 0 :(得分:1)

我有类似的东西,但是我使用转换器来计算TabControl的实际宽度,并将它们平均分配到TabItems之间。在您的View的资源中包含下面的Converter。

转换器

public class EqualWidthConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var numberOfTabs = int.Parse(parameter.ToString());
        var actualWidth = (double)value;
        var equalWidth = actualWidth / numberOfTabs;

        // For TabItem's tiny space after the last tab.
        return equalWidth-2;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

查看

<TabControl Name="Tabct" Height="Auto" Width="Auto">
    <TabItem Header="First Tab" Width="{Binding ActualWidth, ElementName=Tabct, Converter={StaticResource EqualWidthConverter}, ConverterParameter=3}">
    </TabItem>
    <TabItem Header="Second Tab" Width="{Binding ActualWidth, ElementName=Tabct, Converter={StaticResource EqualWidthConverter}, ConverterParameter=3}">
    </TabItem>
    <TabItem Header="Third Tab" Width="{Binding ActualWidth, ElementName=Tabct, Converter={StaticResource EqualWidthConverter}, ConverterParameter=3}">
</TabItem>
</TabControl>