Reputation: 1754
I'm developing windows phone 8 app. I have a customer UserControl
called SelectableButton
. The constructor of it is as below:
public SelectableButton()
{
InitializeComponent();
DataContext = this;
}
The xaml of it is like this:
<Grid>
<TextBlock x:Name="ButtonTextBlock"
Text="{Binding SelectableButtonText, Mode=TwoWay}"
SomeOtherCode
/>
...
</Grid>
The SelectableButtonText
is a property of this UserControl
:
public static readonly DependencyProperty SelectableButtonTextProperty =
DependencyProperty.Register(
"SelectableButtonText", typeof(string),
typeof(SelectableButton),
null
);
Now I use this SelectableButton
in a Pivot
. I want to bind the SelectableButtonText
property to some data. This is the DataTemplate
used in a Pivot
called PivotTestContent
:
<ShareControl:SelectableButton
SelectableButtonText="{Binding question}"
...
>
</ShareControl:SelectableButton>
The question
is from the ItemsSource
of this Pivot
:
PivotTestContent.ItemsSource = quizs;
The quizs
is a List<>
of WCCQuizText
quizs = new List<WCCQuizText>();
And the question
is a property member of WCCQuizText
:
public String question
{
get;
set;
}
After all these work, I find that the Binding
cant find the property question
. It seems that because of this line in the constructor of SelectableButton
:
DataContext = this;
The Binding will look for the property question
in Class SelectableButton
, not from the ItemsSouce
. Because if I bind question
directly to some TextBlock.Text
, it will work. But when I bind it to my UserControl, it can't be found.
So anybody know how to deal with this?
If I do like this, I can show the binding text correctly, the TextBlock is in the Pivot, too.
<TextBlock
Name="TextBlockQuestion"
Text="{Binding question}"
....
>
</TextBlock>
And my Binding:
<ShareControl:SelectableButton
SelectableButtonText="{Binding Text, ElementName=TextBlockQuestion}"
....
>
</ShareControl:SelectableButton>
Upvotes: 1
Views: 224
Reputation: 33364
You are correct. It is caused by DataContext = this
. Normally your UserControl
would have context set to an instance of WCCQuizText
but you are overwriting it with an instance of your UserControl
. Try removing that line, give UserControl
some name and and change your binding, within UserControl
, to something like:
<UserControl x:Name="SomeName" ... >
....
<TextBlock ... Text="{Binding ElementName=SomeName, Path=SelectableButtonText}"
also TextBlock
is display control and it will always be one way binding so you can skip Mode=TwoWay
Upvotes: 2