The dependency property is a property that can be set directly by various different property providers while having them prioritized. The dependency property depends on multiple property providers. Each one of them has its own level of precedence. We use dependency properties just as any other property. There is no need knowing in advance that a property we work with is a dependency property. Some of the available silverlight features (e.g. binding) are limited to dependency properties. The attached properties are sort of dependency properties. Any property that we bind, style, template, transform or animate must be a dependency property. Dependency properties are not always needed. When customizing our application most likely we will eventually end up with the need for having dependency properties. The dependency properties acts as kind of wrappers around a field. The dependency properties are kind of a replacement for a field a standard property wraps.

In order to define a dependency property we should first instantiate the System.Windows.DependencyProperty class. This new object will represent the dependency property. The dependency property needs to be always available and for that reason we define it as a static field in the associated class. The field that defines a dependency property has the name of the ordinary property plus the word Property at its end. This way the dependency property definition is separated from the actual property. The field should be defined redonly. This way its value can be set within the static constructor only.

The next step should be registering the dependency property with the Silverlight platform. We should complete this registration before we start using the property. Therefore, we will usually perform this required registration within the scope of the static constructor we define in the associated class. We create a DependencyProperty instance by calling the static DependencyProperty.Register() method.

The actual storage of the dependency property value is automatically taken care of, deep inside the WPF property system.

The class that contains a dependency properties must derive from DependencyObject. Defining a class that extends UIElement we fulfill this requirement.

The following is a simple code sample for defining a dependency property. You can follow this sample as a template for your own usage.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;

namespace ConsoleApplication14
{
    public class Program
    {
        static void Main(string[] args)
        {
            Book book = new Book();
            book.Title = "Core Python";
            Console.WriteLine("### "+book.Title+" ###");
            book.Title = "abc";
            Console.WriteLine("### " + book.Title + " ###");
            book.Title = "Core PHP";
            Console.WriteLine("### " + book.Title + " ###");
            book.Title = "a";
            Console.WriteLine("### " + book.Title + " ###");
        }
    }
    public class Book : DependencyObject
    {
        public static readonly DependencyProperty TitleProperty =
            DependencyProperty.Register(
                "Title", 
                typeof(string), 
                typeof(Book),
                new PropertyMetadata(
                    "No Name", TitleChangedCallback, TitleCoerceCallback),
                TitleValidateCallback);

        private static void TitleChangedCallback(
            DependencyObject obj, DependencyPropertyChangedEventArgs e)
        {
            Console.WriteLine("Log Message: within TitleChangedCallback");
            Console.WriteLine(e.OldValue + " " + e.NewValue);
        }

        private static object TitleCoerceCallback(DependencyObject obj, object o)
        {
            Console.WriteLine("Log Message: within TitleCoerceCallback");
            string str = o as string;
            //here we can validate the title and change it if needed
            if(str.Length>0)
            {
                Console.WriteLine("new title is OK");
            }
            else
            {
                Console.WriteLine("new title is not OK");
                Console.WriteLine("will set 'no name' instead");
                str = "no name";
            }
            return str;
        }

        private static bool TitleValidateCallback(object value)
        {
            Console.WriteLine("Log Message: within TitleValidateCallback");
            //return true if there is a place to call the validation method
            return value != null && ((string) value).Length > 2;
        }

        public string Title
        {
            get
            {
                return (string)GetValue(TitleProperty);
            }
            set
            {
                SetValue(TitleProperty, value);
            }
        }
    }

}

The following video clip explains the above code sample.

Leave a Reply

Your email address will not be published. Required fields are marked *