【问题标题】:WP7 Pivot Title Template DataContext Binding not workingWP7 枢轴标题模板 DataContext 绑定不起作用
【发布时间】:2011-03-24 16:45:01
【问题描述】:

我有一个 Pivot Title 模板,因此 Pivot 页面有一个标题和副标题。我想通过代码设置两者。

我在 Blend 中构建 XAML,没有代码绑定,它确实显示,因此该部分工作。

但是,我的绑定不起作用。它要么不会构建,因为对象没有 DataContext,要么对象不存在于当前上下文中,要么会构建但不会显示。当它不显示时,我假设我绑定到了错误的 XAML 对象。每个对象都被命名,所以我可以找到正确的对象来绑定。

Title 和 Subtitle 绑定代码的包含类如下所示:

public class PivotTitle
{
    public string Title = "";
    public string Subtitle = "";
}

我的问题是:如何正确绑定 TitleTemplate 以便在代码中设置两个 TextBlocks 的 Text 属性?

这里是 XAML

       <controls:Pivot.TitleTemplate >
            <DataTemplate x:Name="PivotTitleTemplateDataTemplate"  >
                <StackPanel x:Name="MyPivotTitle" DataContext="{Binding}" >
                    <TextBlock x:Name="Title"
                        Text="{Binding Title}"
                        FontSize="20"
                        TextWrapping="Wrap"/>
                    <TextBlock x:Name="Subtitle"
                        Text="{Binding Subtitle}"
                        Foreground="Gray"
                        TextWrapping="Wrap"/>
                </StackPanel>
            </DataTemplate>
        </controls:Pivot.TitleTemplate>

标题和副标题取决于导航的页面。后面的代码如下:

//定义在页面类的顶部 public PivotTitle _PivotTitle = new PivotTitle();

    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);


        string queryStringDeploymentName = "";

        this.NavigationContext.QueryString.ContainsKey("DeploymentName"))

        _PivotTitle.Title = SelectedDeployment.DeploymentName;
        _PivotTitle.Subtitle = App.ViewModel.AppSettings.UpdatedText;
       MyPivotTitle.DataContext = _PivotTitle;
     }

此特定示例不会生成此错误:名称“MyPivotTitle”在当前上下文中不存在。 Pivot 页面的列表框上的绑定工作正常。

我相信我的代码隐藏和整体 XAML 是正确的。我认为我的 DataContext 绑定不正确。

感谢您的帮助。

【问题讨论】:

    标签: templates windows-phone-7 binding pivot title


    【解决方案1】:

    在您的示例中,MyPivotTitle 是 DataTemplate 中的一个元素,因此无法直接从您的代码中访问,因此会出现错误。如果您需要访问项目控件模板内的控件(例如 Pivot 或 ListBox`),那么您可能会发现来自 WIndowsPhoneGeek.com 的 this article 很有用。

    但是,听起来您可以在没有任何“黑客行为”的情况下做到这一点。此标题和副标题是否仅适用于单个枢轴项目,还是会出现在所有项目上?您还绑定了哪些其他数据(如果有)?

    【讨论】:

    • 这个想法是根据显示的枢轴通过代码在应用程序的枢轴上统一控制标题和副标题。理想情况下,一个单独的代码类来管理它,而不是触及后面的每个枢轴页面代码。似乎我应该能够在应用程序级别执行此操作,但我陷入了新的 Silverlight 中。
    猜你喜欢
    • 2014-01-30
    • 1970-01-01
    • 1970-01-01
    • 2011-06-26
    • 2021-06-15
    • 2011-05-15
    • 1970-01-01
    • 2019-01-05
    • 2013-12-24
    相关资源
    最近更新 更多