Bind to Property of Parent Element in Silverlight

11,855

Solution 1

interestingly, the XAML I posted in the original question works correctly in VS2010, so I assume that this is something that has been fixed in the latest Silverlight

Solution 2

Try this:

<UserControl ... Background="Green" x:Name="root">    
  <Grid x:Name="LayoutRoot" Background="White">        
    <Rectangle x:Name="indicatorRectangle" 
         Fill="{Binding Background, ElementName=root}" Width="10" Height="10"  />
  </Grid>
</UserControl>

It didn't work for me until I gave the rectangle a width and height.

Solution 3

Keep in mind that this code will break if you use the user control and set the name (in Silverlight 4.0, Visual Studio 10) with x:Name=.

Share:
11,855
Mark Heath
Author by

Mark Heath

I'm the creator of NAudio, an open source audio library for .NET. I'm interested in any ways to improve the quality of my code, and teaching others the things I learn along the way. I'm also the author of several Pluralsight courses.

Updated on June 04, 2022

Comments

  • Mark Heath
    Mark Heath almost 2 years

    I am trying to bind a property of an element within a UserControl to a property set on the UserControl itself in Silverlight. I'm sure it should be simple, but I haven't managed to get it working with either RelativeSource or ElementName binding. In this example I want the Rectangle to be Green (or whatever the UserControl's Background property gets set to).

    <UserControl x:Class="MyUserControl"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        Width="40" Height="40" Background="Green" x:Name="root">
        <Grid x:Name="LayoutRoot" Background="White">
            <Rectangle x:Name="indicatorRectangle" Fill="{Binding Path=Background, ElementName=root}" Margin="0,0,26,0"  />
        </Grid>
    </UserControl>
    

    anyone know the correct binding syntax?