Binding to a Dependency Property in UserControl? RRS feed

  • General discussion

  •  Hi there, I apologise for my noobness I haves just started Silverlight and need some help on a UserControl.

     I am creating a user control that contains a rectanngle that must display the color I have bound to it.

        <Rectangle x:Name="displayRectangle" RadiusX="3" RadiusY="3" Fill="{Binding Path=Color}" Stroke="{StaticResource BorderBrush}" .../> 
     Here is the C# code that sets up the dependency property.  
       public static readonly DependencyProperty ColorProperty = DependencyProperty.Register("Color", typeof(Brush), typeof(ColorDisplay), null);
    public event PropertyChangedEventHandler PropertyChanged;

    public Brush Color
    get { return (Brush)GetValue(ColorProperty); }
    set { SetValue(ColorProperty, value); displayRectangle.Fill = (Brush)value; }

    private void NotifyPropertyChanged(string szProperty)
    if (PropertyChanged != null)
    PropertyChanged(this, new PropertyChangedEventArgs(szProperty));

    public ColorDisplay()
    // Required to initialize variables

     The bold text I know is wrong and bad design, but without it the rectangle has no fill?!? How do I hook the Fill to the Color dependency property.


    <MyProject:ColorDisplay ... Color="{StaticResource TheBlue}"/>
      This is How I created my user control on the form.
    Monday, May 4, 2009 11:13 AM

All replies

  • Instead of Binding, use TemplateBinding (I gather that the Color property is declared on your control):

    Fill="{TemplateBinding Color}". You shouldn't need to do anything in the setter.

    Secondly, the reason it doesn't work for you is because when you use binding, it actually never calls the setter, but calls base.SetValue directly. Instead your DP should have a static OnChanged handler, where you react to changes to the value.

    Monday, May 4, 2009 4:41 PM
  • Thanks for the Reply, unfortunately if I use {TemplateBinding Color} blend complains about "The member "Color" is not recognised or is not accessible". As far as I know TemplateBinding only works is you are developing Controls not UserControls.

    If I break on the setter I see that it is called and is getting the value bound too it.

    Tuesday, May 5, 2009 3:05 AM