Thursday, March 3, 2011

Binding to an element within a UserControl

Say I have a user control like the one below, how would I bind something to the ActualWidth of the "G1" grid from outside of the control?

<UserControl x:Class="Blah">
  <WrapPanel>
    <Grid x:Name="G1">
      ...
    </Grid>
    <Grid>
      ...
    </Grid>
  </WrapPanel>
</UserControl>
From stackoverflow
  • Can you expose the ActualWidth as a public property and set it in your parent's page for example?

  • If you want to bind to an external control where you use this user control, declare a DependancyProperty at your UserControl code behind and then Bind G1 to that property. And bind the external control's property to the UserControl's Dependancy propery. It is like a 2 level of indirection.

    MJS : but ActualWidth won't bind in this way?
    MJS : a related question: http://stackoverflow.com/questions/313124/wpf-usercontrol-expose-actualwidth
  • If you mean with outside the control, not as Content of the control, you can use ElementName in the Binding like so:

    {Binding ElementName=G1, Path=ActualWidth}
    

    If you mean outside the control in another Xaml file, then you can try to use the Path property if your control is in the scope of the other control:

    {Binding ElementName=ParentControl, Path=G1.ActualWidth}
    

    However I would advise against this design, because you may change the name of G1 one day, and you would never know of any Bindings that might break...

    HTH

    MJS : {Binding ElementName=ParentControl, Path=G1.ActualWidth} doesn't work & the control is in scope - I can see the actual width of the whole control.

0 comments:

Post a Comment