WPF Dependency properties have an interesting flag that you can specify when registering property:
FrameworkPropertyMetadataOptions.Inherits

Specifying this flag allows property value to propagate through the parent tree. That means you can have property that will have its value synced with the parent (does not have to be immediate parent) completely automatically. There is small performance penalty for this of course, but for certain usage scenarios it is very useful.

Using this is not that straight forward since there are some rules that need to be followed to implement property with inheritable values. Here they are:

  • On parent, dependency property must be defined as attached property. You can still declare property getter/setter, but property must be attached. Here is simple declaration:
public static readonly DependencyProperty InheritedValueProperty =
   DependencyProperty.RegisterAttached("InheritedValue",
   typeof(int), typeof(MyClass), new FrameworkPropertyMetadata(0, 
   FrameworkPropertyMetadataOptions.Inherits));
public static int GetInheritedValue(DependencyObject target)
{
   return (int)target.GetValue(InheritedValueProperty);
}
public static void SetInheritedValue(DependencyObject target, int value)
{
   target.SetValue(InheritedValueProperty, value);
}
public int InheritedValue
{
   get
   {
      return GetTimeSlotDuration(this);
   }
   set
   {
      SetTimeSlotDuration(this, value);
   }
}

  • Child objects would define their instance of the property with inherited value using AddOwner. Following is the code that goes into say MyChildClass sample class:
public static readonly DependencyProperty InheritedValueProperty;
public int InheritedValue
{
   get
   {
      return (int)GetValue(InheritedValueProperty);
   }
   set
   {
      SetValue(InheritedValueProperty, value);
   }
}
static MyChildClass()
{
   InheritedValueProperty = MyClass.InheritedValueProperty.AddOwner(typeof(MyChildClass),
      new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.Inherits));
}

Note that property is in child class declared as standard dependency property and that it specifies Inherit in meta-data options.

With setup like this now when MyChildClass in parented to MyClass visually or logically they will share the same property value automatically.

Professional looking applications made easy with DotNetBar for WinForms, Silverlight and WPF User Interface components. Click here to find out more.