在运行时使用c#创建自定义的PivotItem头

本文关键字:自定义 PivotItem 创建 运行时 | 更新日期: 2023-09-27 18:15:11

我试图在加载时动态地将pivotiitem添加到Pivot。我需要一些屏幕空间和标准pivot项目标题字体对我来说太大了。一些论坛搜索得出了这样的解决方案:

<controls:PivotItem>
   <controls:PivotItem.Header>
      <TextBlock FontSize="{StaticResource PhoneFontSizeLarge} Text="MyHeaderText"/>
   </controls:PivotItem.Header>
</controls:PivotItem>

如果我在数据透视项XAML本身中定义它,这个解决方案可以正常工作,但是我如何在c#代码中做到这一点?

在运行时使用c#创建自定义的PivotItem头

您只需要创建一个Pivot对象和一些PivotItems对象,然后将这些PivotItems添加到Pivot。最后将Pivot添加到可能是GridLayoutRoot中。

像这样,

    void PivotPage2_Loaded(object sender, RoutedEventArgs e)
    {
        var pivot = new Pivot();
        var textBlock = new TextBlock { Text = "header 1", FontSize = 32 };
        var pivotItem1 = new PivotItem { Header = textBlock };
        var textBlock2 = new TextBlock { Text = "header 2", FontSize = 32 };
        var pivotItem2 = new PivotItem { Header = textBlock2 };
        pivot.Items.Add(pivotItem1);
        pivot.Items.Add(pivotItem2);
        this.LayoutRoot.Children.Add(pivot);
    }

以下代码将Pivot中所有现有PivotElementFontSize设置为给定值。它还(大致)调整标题区域的高度。

代码深入Pivot的子节点,并搜索要修改的正确项:PivotHeaderItem(单个头)和PivotHeadersControl(包含所有头)。

using Microsoft.Phone.Controls.Primitives;
delegate void ChildProc(DependencyObject o);
// applies the delegate proc to all children of a given type
private void DoForChildrenRecursively(DependencyObject o, Type typeFilter, ChildProc proc)
{
    // check that we got a child of right type
    if (o.GetType() == typeFilter)
    {
        proc(o);
    }
    // recursion: dive one level deeper into the child hierarchy
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(o); i++)
    {
        DoForChildrenRecursively(VisualTreeHelper.GetChild(o, i), typeFilter, proc);
    }
}
// applies the given font size to the pivot's header items and adjusts the height of the header area
private void AdjustPivotHeaderFontSize(Pivot pivot, double fontSize)
{
    double lastFontSize = fontSize;
    DoForChildrenRecursively(pivot, typeof(PivotHeaderItem), (o) => { lastFontSize = ((PivotHeaderItem)o).FontSize; ((PivotHeaderItem)o).FontSize = fontSize; });
    // adjust the header control height according to font size change
    DoForChildrenRecursively(pivot, typeof(PivotHeadersControl), (o) => { ((PivotHeadersControl)o).Height -= (lastFontSize - fontSize) * 1.33; });
}
private void button1_Click(object sender, RoutedEventArgs e)
{
    // make header items having FontSize == PhoneFontSizeLarge
    AdjustPivotHeaderFontSize(pivot, (double)Resources["PhoneFontSizeLarge"]);
}

如果你想知道标题高度计算中的*1.33是从哪里来的-它是受到这篇博客文章的启发。