Tuesday, February 21, 2012

Windows Phone - Dependency Properties (11)

Hello

Dependency property give support for :

  • Data binding
  • Property change notification
  • Use in styles


A class that implement DependencyProperty must inherit the class DependencyObject DependencyObject is very common -  UIElement derive it

Register is an important static method to register dependency property . Arguments :
  • Name of dependency property
  • Type of property
  • Type of owner i.e. the class 
  •  Property metadata. Used e.g. for   PropertyChangedCallback

Return is DependencyProperty which should be set to public static readonly field in the owner class.

Source sample
DependencyProperty_NK.zip

PropertyLimitation.xaml
The page is composed of four TextBox.Two are using CSimpleGardientTextBox and two are using CBetterGradientTextBox both are using RadialGradientBrush



The style styleCGradientTextBox is defined with three colors Brown,White,Pink



CSimpleGradientTextBox.cs
CSimpleGradientTextBox is a TextBox wirh RadialGradientBrush as background. The class has properties Color1,Color2,Color3 which defines the colors of the gradient stops



CSimpleGradientTextBox has one limitation - it can not be used as Style because you will not be able to set Color1,Color2,Color3. To be able to do this you need DependencyProperty

CBetterGradientTextBox.cs
CBetterGradientTextBox overcome the limitation of CSimpleGradientTextBox  by using dependency properties.




Basically all properties Color1,Color2,Color3 are handled the same way so i will show handling one property - Color1.

Color1Property is defined as DependencyProperty by specifying :

  • The property - Color1
  • Type of Color1 - Color
  • Type of owner - CBetterGradientTextBox
  • Hanlder - OnColor1Changed , default color  of Color1 - Red


Color1 is defined using DependencyObject methods SetValue and GetValue.  It is common to say that property Color1 is backed by dependency property Color1Property.

Handler is defined 

Note that OnColor1Changed is called whenever Color1 value is changed via it's set. This is possible because set calls the DependencyObject's method - SetValue


Run the application, click the "PropertyLimitation" button to produce




First TextBox  -  colors Brown,White,Red are defined in XAML
Second TextBox - colors are not defined in XAML so the default values in the constructor Red,Green,Blue are used
Third TextBox - style is used. Colors Brown,WhitePink
Forth TextBox -  colors are not defined in XAML, colors Red, Green,Blue defined in Register are taken



Attached Properties
Attached properties is the ability of child element in XAML to set its parent property. E.g. Canvas layout has it's property Left,Top set on it's children e.g.



It is defined using the method RegisterAttached of  DependencyProperty



Nathan

No comments:

Post a Comment