Introducing Custom DependencyProperty in WPF

In this sample code I want to introduce three DependencyProperty called Overlap Rotation and UpperOffset in a custom control OverlapStackPannel. The control is simply a StackPanel that arranges the containing items in a custom manner.

In the ArrageOverride method I will use these three properties to locate each item as follows:

   protected  override  System.Windows.Size  ArrangeOverride(System.Windows.Size  arrangeSize)
   {
     UIElementCollection  children = this.InternalChildren;

    int  childrenResolved = 0;
    foreach  (UIElement  child in  children)
    {
 Rect  targetRect = new  Rect ();
 targetRect.X = this .Overlap * childrenResolved;
 targetRect.Y = this .UpperOffset;
 targetRect.Width = child.DesiredSize.Width;
 targetRect.Height = child.DesiredSize.Height;
 child.Arrange(targetRect);
 child.RenderTransform = new  RotateTransform (this .Rotation);
 childrenResolved++;
    }
    return  arrangeSize;
   }


To Achieve this I need to set the properties as follows:

  #region  Property: UpperOffset
  public  static  readonly  DependencyProperty  UpperOffsetProperty = DependencyProperty .Register("UpperOffset" , typeof (double ), typeof (OverlapStackPanel ), new  FrameworkPropertyMetadata (double .NaN, FrameworkPropertyMetadataOptions .AffectsArrange));
      
  /// <summary> 
  /// set or get the upper offset for each item in the pannel 
  /// </summary> 
  public  double  UpperOffset
  {
    get 
    {
      return  (double )this .GetValue(OverlapStackPanel .UpperOffsetProperty);
    }
    set 
    {
      this .SetValue(OverlapStackPanel .UpperOffsetProperty, value );
    }
  }
  #endregion 

and similar for other two.
This makes my OverlapStackPanel having the properties in Blend like this:

Benefits

According to this nice article there are three main advantages of using DependencyProperties comparing to CLR properties:

  • Reduced memory footprint
  • Value inheritance
  • Change notification