Monday, January 23, 2012

Poor Man's Implementation of Dependency Object

Points to Note:
* Dependency Object is an abstract class. In only provides helper methods to deriving classes to be able to use Dependency property (Well, that is a lot of work because DependencyObject also takes care of the facilities provided by DependencyProperty).
* We have one instance of DependecyObject for each control. Thus, one instance of DependencyProperty-Value map. That makes it easy for a control to be able to store and retrieve value for a any dependency property.
* Again, DependencyObject maintains an instance level mapping between dependecyProperty and it's value (if not set by user/control then uses the default value - saves memory)
* How are attached properties stored in DependencyObject ? It's the same. For attached properties controls create a wrapper static property which accepts DependencyObject and then call Set/Get on the dependencyObject. Both of the set methods are passed the target object to which the property is to be attached (Note: In all this process there is NO role of the instance of the object which has defined the attached property).
* Is it allowed to Register a property in one type with owner as another type? Looks like yes, it is possible. Of course with condition that the owner does not already register a property with same name.


public abstract class MockDependenctObject
    {
        private readonly Dictionary _dp2Value;

        protected MockDependenctObject()
        {
            _dp2Value = new Dictionary();
        }

        public void SetValue(MockDependencyProperty dependencyProperty,object value)
        {
            _dp2Value[dependencyProperty] = value;
        }

        public object GetValue(MockDependencyProperty dependencyProperty)
        {
            if(_dp2Value.ContainsKey(dependencyProperty))
            {
                return _dp2Value[dependencyProperty];
            }
            return null;
        }


    }

No comments:

Post a Comment