What is a DependencyProperty in SIlverlight and How to implement it?

What is a DependencyProperty and How to implement it?  Please explain in detail with an example.
Who is Participating?
apeterConnect With a Mentor Commented:
you can have custom Property to any existing control for example Textbox. You can access this property in XAML or code behind. Actually all default properties of textbox are dependency properties

for ex. lets say i want to have custom property called Maxlength for my TexBox. We should have below codes.

public static readonly DependencyProperty MaxLengthProperty =
            //the name u want to appear in inetllisense in xaml
             //under which class you have this dependcy property, here i have a custom textbox control class
            //default value for this property
            new PropertyMetadata(0));

        public int MaxLength
            get { return (int)GetValue(MaxLengthProperty); }

                //have your custom validations here which will be captured in runtime.
                if (!int.TryParse(value.ToString(), out i))
                    throw new ArgumentException("Invalid MaxLength Argument");
                if (i < 1)
                    throw new Exception("Max Legth value should be greater than Zero");
                SetValue(MaxLengthProperty, value);

now u can access MaxLength to get value from XAML or set value in code behind. The same can be used in Binding as well.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.