Monday, December 6, 2010

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.RenderTransform = new  RotateTransform (this .Rotation);
    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
      return  (double )this .GetValue(OverlapStackPanel .UpperOffsetProperty);
      this .SetValue(OverlapStackPanel .UpperOffsetProperty, value );

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


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

  • Reduced memory footprint

  • Value inheritance

  • Change notification