简体   繁体   中英

How to bind WP7 user control element to a property of the user control

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM