Reputation: 46350
I've built a user control called UserControl1. Inside the control I havea textblock. In the UserControl1 class, I've created a property called DisplayText. How can I bind the textblock's text value to the DisplayText property of the user control?
Upvotes: 0
Views: 1078
Reputation: 70142
If you have a UserControl as follows:
<UserControl class="MyUserControl">
<Grid x:Name="LayoutRoot">
<TextBlock/>
</Grid>
</UserControl>
And MyUserControl defines a DisplayText
dependency property. Within the constructor set the DataContext
of LayoutRoot
to the user control:
public MyUserControl()
{
LayoutRoot.DataContext = this;
}
You can now bind the TextBlock
as follows:
<UserControl class="MyUserControl">
<Grid x:Name="LayoutRoot">
<TextBlock Text="{Binding Path=DisplayText}/>
</Grid>
</UserControl>
This works because the DataContext
of the grid is inherited by your TextBlock
. This then becomes the source of the binding.
Upvotes: 2