【问题标题】:Change pivot header at runtime在运行时更改数据透视表头
【发布时间】:2013-11-10 03:38:45
【问题描述】:

我想在运行时设置数据透视表头。 以下解决方案适用于第一项。

 StackPanel sp = new StackPanel();
 TextBlock tb1 = new TextBlock();
 tb1.Text = "bla";
 TextBlock tb2 = new TextBlock();
 tb2.Text = "blub";

 sp.Children.Add(tb1);
 sp.Children.Add(tb2);

 PivotItem pivotitem = new PivotItem { Header = sp };

 WorkoutPivot.Items.Add(pivotitem);

在两个或多个项目上,它会抛出异常:“值不在预期范围内。”

我需要另一种方法来做到这一点。

谢谢, 鲁文

【问题讨论】:

    标签: c# windows-phone-7 windows-phone-8 windows-phone pivot


    【解决方案1】:

    如果您想(重新)定义 Pivot 标头的外观,则必须使用 Pivot.HeaderTemplate 类型为 DataTemplate 的属性(这将影响其所有 PivotItems 子级)。

    PivotItem.Header 属性不能做到这一点,它不是模板,而是包含要绑定到每个 PivotItem 的标头 DataTemplate 的数据的对象。

    所以理论上,您必须在您的代码(及其所有内容)中创建一个DataTemplate,然后将其分配给您的Pivot.HeaderTemplate 属性。

    一个解决方案可能是article 中解释的以下解决方案:

    1. 像这样创建您的 DataTemplate(或从资源中检索它):

      string xaml =
        @"<DataTemplate
        xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
        xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
        <StackPanel>
            <TextBlock Text='bla' />
            <TextBlock Text='blub' />
        </StackPanel>        
        </DataTemplate>";
    DataTemplate dt = (DataTemplate)XamlReader.Load(xaml);
    

    2. 然后将dt 分配给您的Pivot.HeaderTemplate 属性:

    yourPivot.HeaderTemplate = dt;
    

    话虽如此,并确保它确实是您所需要的

    如果您不想更改 Pivot 标头的外观,而只想更改与标头 DataTemplate 绑定的内容(包含的文本等等...),那么您只需为你的PivotItem.Header 属性。

    例如带有标题DataTemplate,如下所示:

       <DataTemplate
            xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
            xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"">
            <StackPanel>
                <TextBlock Text='{Binding Test1}' />
                <TextBlock Text='{Binding Test2}' />
            </StackPanel>        
       </DataTemplate>
    

    还有这样的 POCO:

        public class TestPOCO
        {
            public string Test1 { get; set; }
            public string Test2 { get; set; }
        }
    

    您可以更改您的 PivotItem.Header 内容:

    yourPivotItem.Header = new TextPOCO { Test1 = "newValue1", Test2 = "newValue2"};
    

    【讨论】:

    • 谢谢 :) 你知道,如果我的数据透视项有一个属性,它代表内容吗?如果我使用 pivotitem.Content = new TextPOCO,我认为它会覆盖数据模板。
    • “内容”到底是什么意思:可视化树还是绑定数据?
    • 我找到了解决问题的方法 :) 我的意思是来自我的数据透视项的绑定数据。
    猜你喜欢
    • 2017-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-27
    • 2020-01-13
    • 1970-01-01
    相关资源
    最近更新 更多