views:

10

answers:

1

First Control I can create a UserControl with a DependencyProperty called UserNameLabel. Then, I can just set the datacotext to relativesource self on the UserControl and fill the property in markup.

...

       public String UserNameLabel
    {
        get { return (String)GetValue(UserNameLabelProperty); }
        set { SetValue(UserNameLabelProperty, value); }
    }

    // Using a DependencyProperty as the backing store for UserNameLabel.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty UserNameLabelProperty =
        DependencyProperty.Register("UserNameLabel", typeof(String), typeof(LoginControl), new PropertyMetadata());


     <Grid x:Name="LayoutRoot"> 
     <local:LabelTextBox Height="37" Margin="10,24,43,0" VerticalAlignment="Top" Label="{Binding UserNameLabel}"/>
 </Grid>

...

Second Control I can also create a LabelTextBox control and set the relativesource self to it with a similar Label Property.

...

        public String Label
    {
        get { return (String)GetValue(LabelProperty); }
        set { SetValue(LabelProperty, value); }
    }

    // Using a DependencyProperty as the backing store for Label.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty LabelProperty =
        DependencyProperty.Register("Label", typeof(String), typeof(LabelTextBox), new PropertyMetadata(String.Empty));

...

   <Grid x:Name="LayoutRoot">
    <TextBlock Height="17" VerticalAlignment="Top" TextWrapping="Wrap" Text="{Binding Label}"/>

However, if I want to nest the LabelTextBox in the first usercontrol I can't seem to put a binding on the Label Property of the LabelTextBox that binds to the UserNameText Property.

It seems like a logical way to create controls where you can set the property of the parent or child control to set the child control's property.

Please help me with this.

A: 

No this is not a good approach, you should not assume you have control over any publically available property of a UserControl, that includes the DataContext.

When I want to bind a property of an element to a property of the containing UserControl I use this approach:-

 <Grid x:Name="LayoutRoot">
   <TextBlock Text="{Binding Parent.Label, ElementName=LayoutRoot}" />
 </Grid>

This uses ElementName to set the binding source to the Child of the UserControl. The Parent in the property path then finds the UserControl itself after which we can bind to whatever property that is needed, in this case the Label property.

In this approach you need not muck about with the DataContext.

AnthonyWJones