我用FrameworkPropertyMetadataOptions.Inherits声明了一个依赖属性: public static class DesignerItemStyles { public static readonly DependencyProperty HeaderBackgroundProperty = DependencyProperty.RegisterAttached( "HeaderBackgrou
public static class DesignerItemStyles {
public static readonly DependencyProperty HeaderBackgroundProperty =
DependencyProperty.RegisterAttached(
"HeaderBackground", typeof(Brush), typeof(DesignerItemStyles),
new FrameworkPropertyMetadata(
Brushes.DesignerViewElementHeaderBackground,
FrameworkPropertyMetadataOptions.Inherits));
/* Below are Get & Set as usual */
}
它有点工作,但不知何故不是整个视觉树.以下是显示从HeaderedDesignerItemChrome继承值的ContentPresenter的屏幕截图:
现在,屏幕截图显示ContentPresenter的内容,并且它不会继承该值.它也没有被设置为其他东西 – 它是默认值:
知道为什么吗?
使用它并不是那么简单,因为有一些规则需要遵循以实现具有可继承值的属性.他们来了:在父级上,依赖属性必须定义为附加属性.您仍然可以声明属性getter / setter,但必须附加属性.这是简单的声明:
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);
}
}
子对象将使用AddOwner定义具有继承值的属性实例.以下是MyChildClass示例类的代码:
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));
}
如果使用单个参数重载,则保留全局默认值并且继承仍然有效…
MyClass.InheritedValueProperty.AddOwner(typeof(MyChildClass));
请注意,属性在子类中声明为标准依赖项属性,并且它在元数据选项中指定Inherit.
现在,当MyChildClass以可视方式或逻辑方式成为MyClass的父级时,它们将自动共享相同的属性值.
所以从技术上讲,你在Visual Tree中看到的就是做你告诉它要做的事情.它设置了您告诉它的默认值,并且继承的控件继承自您的ContentPresenter的父值
