【问题标题】:User Control in Pivot, binding not work枢轴中的用户控件,绑定不起作用
【发布时间】:2014-01-30 15:48:17
【问题描述】:

我正在开发 windows phone 8 应用程序。我有一个客户UserControlSelectableButton。它的构造函数如下:

public SelectableButton()
{
    InitializeComponent();
    DataContext = this;
}  

它的xaml是这样的:

<Grid>    
    <TextBlock x:Name="ButtonTextBlock"                  
        Text="{Binding SelectableButtonText, Mode=TwoWay}"
        SomeOtherCode
    />
    ...
</Grid>    

SelectableButtonText 是这个UserControl 的属性:

    public static readonly DependencyProperty SelectableButtonTextProperty =  
DependencyProperty.Register(
                "SelectableButtonText", typeof(string), 
                typeof(SelectableButton),
                null
                );

现在我在Pivot 中使用这个SelectableButton。我想将SelectableButtonText 属性绑定到一些数据。这是Pivot 中使用的DataTemplate,称为PivotTestContent

<ShareControl:SelectableButton
    SelectableButtonText="{Binding question}"
    ...
    >
</ShareControl:SelectableButton>

question 来自这个ItemsSourcePivot

PivotTestContent.ItemsSource = quizs;

quizsList&lt;&gt;WCCQuizText

quizs = new List<WCCQuizText>();

questionWCCQuizText 的属性成员:

public String question
{
    get;
    set;
}

完成所有这些工作后,我发现Binding 找不到属性question。似乎是因为SelectableButton的构造函数中的这一行:

DataContext = this;

绑定将在SelectableButton 类中查找属性question,而不是从ItemsSouce。因为如果我将question 直接绑定到某个TextBlock.Text,它将起作用。但是当我将它绑定到我的 UserControl 时,它就找不到了。 那么有人知道如何处理吗?


如果我这样做,我可以正确显示绑定文本,TextBlock 也在 Pivot 中。

   <TextBlock
       Name="TextBlockQuestion"
       Text="{Binding question}"
       ....
       >
   </TextBlock>

还有我的绑定:

<ShareControl:SelectableButton
    SelectableButtonText="{Binding Text, ElementName=TextBlockQuestion}"
    ....
    >
</ShareControl:SelectableButton>

【问题讨论】:

    标签: c# windows-phone-7 data-binding windows-phone-8


    【解决方案1】:

    你是对的。它是由DataContext = this 引起的。通常您的UserControl 会将上下文设置为WCCQuizText 的实例,但您将用UserControl 的实例覆盖它。尝试删除该行,给UserControl 一些名称,然后将UserControl 中的绑定更改为:

    <UserControl x:Name="SomeName" ... >
       ....
       <TextBlock ... Text="{Binding ElementName=SomeName, Path=SelectableButtonText}"
    

    TextBlock 也是显示控件,它始终是单向绑定,因此您可以跳过 Mode=TwoWay

    【讨论】:

    • 嗨@dkozl,感谢您的快速回复。为什么我添加 DataContext = this;在我的用户控件的构造函数中是因为我必须将一些控件的属性绑定到它的 DependencyProperties,而不仅仅是文本。所以我想如果我删除这一行,我必须在 xaml 中做一些工作。有什么建议吗?
    • 如果你删除DataContext = this;并给UserControl一个名字,你可以绑定其他控件属性,就像SelectableButtonText这样ElementName。这就是您可以保持当前DataContext 并仍然绑定UserControl 属性的方法。
    • 嗨@dkozl,我想我现在明白你的意思了!非常感谢。
    • 嗨@dkozl,你的建议很有效。但是我发现通过这种方法,UI的出现变慢了。显示我的用户控件需要一秒钟。如果我使用DataContext = this; ,它很快。你知道为什么吗?谢谢。
    • 我没有遇到使用ElementName 引起的任何性能问题。两种情况下的时间应该相同。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多