Event Driven Classes - Dependency Properties

Sometimes when implementing a class you expose a property which is a calculated value, dependent on one or more other values stored in the class.

When one of the values your calculation depends on changes, you need to raise a PropertyChanged event on your class to signal that the calculated property has also changed.

MetaPropertyHost provides a protected method with the following signature to hook this up automatically:

    protected void CreateDependency(
        string targetPropertyName, 
        params IObservable[] sourceObservables);


The usage is very simple; the first parameter is your calculated property, and the remaining parameters are the source objects which implement IObservable (for example Observable`1 or IMetaProperty).

There is also a version which takes a lamda expression to avoid using strings, as the following example shows:

    public class Cat : MetaPropertyHost
    {
        private readonly Observable<int> observableAgeInMonths = new Observable<int>();

        public Cat()
        {
            // Hook up the dependent property.
            this.CreateDependency(() => this.AgeInYears, this.observableAgeInMonths);
        }

        public int AgeInMonths
        {
            get { return this.observableAgeInMonths.Value; }
            set { this.observableAgeInMonths.Value = value; }
        }

        public IMetaProperty<int> AgeInMonthsProperty
        {
            get { return this.observableAgeInMonths.MetaProperty; }
        }

        // This is our dependent property.
        public double AgeInYears
        {
            get
            {
                return this.AgeInMonths / 12.0;
            }
        }
    }


In the above case the AgeInYears property is dependent on the observableAgeInMonths container. After creating the dependency, whenever the observableAgeInMonths container is updated the class automatically raises a PropertyChanged event for AgeInYears as well as AgeInMonths.

Last edited Mar 9, 2010 at 2:15 PM by jamesthurley, version 2

Comments

No comments yet.