如何更改继承的依赖项属性的默认值?

如何更改继承的依赖项属性的默认值?

问题描述:

如何更改继承的依赖项属性的默认值?在我们的示例中,我们创建了Control的子类,默认情况下,该子类的 Focusable 设置为 true。我们希望子类的默认值为'false'。

How can I change the default value for an inherited dependency property? In our case, we've created a subclass of Control which by default has its Focusable set to 'true'. We want our subclass to have the default of 'false'.

我们一直在做的只是在构造函数中将其设置为'false',但是如果有人使用ClearValue,它返回到默认值,而不是构造函数中设置的值。

What we've been doing is simply setting it to 'false' in the constructor, but if someone uses ClearValue, it goes back to the default, not the value set in the constructor.

这是我目前正在实现此目的的方法(这是一个带有例如, Foo的DP。)我不喜欢隐藏属性的 new,尽管感谢 AddOwner ,它确实指向相同的共享实例,所以我想还可以。看起来它也继承了所有其他元数据值,所以很好。只是想知道这是否正确?

Here's what I'm currently doing to achieve this (This is a test control with a DP of 'Foo' for an example.) I'm not a fan of the 'new' to hide the property although thanks to AddOwner, it does point to the same shared instance so I guess it's ok. It looks like it inherits all the other metadata values as well so that's good. Just wondering if this is correct?

public class TestControlBase : Control
{

    public static readonly DependencyProperty FooProperty = DependencyProperty.Register(
        "Foo",
        typeof(int),
        typeof(TestControlBase),
        new FrameworkPropertyMetadata(4) // Original default value
    );

    public int Foo
    {
        get { return (int)GetValue(FooProperty); }
        set { SetValue(FooProperty, value); }
    }

}

public class TestControl : TestControlBase
{

    public static readonly new DependencyProperty FooProperty = TestControlBase.FooProperty.AddOwner(
        typeof(TestControl),
        new FrameworkPropertyMetadata(67) // New default for this subclass
    );

}

Mark

更新...

我认为这样做更好,因为它消除了新调用。您仍然可以通过基类上的FooProperty访问它,因为它使用了 AddOwner

I think this is even better as it eliminates the 'new' call. You still access it via the FooProperty on the base class since this uses AddOwner. As such, it's technically the same one.

public class TestControl : TestControlBase
{
    // Note this is private
    private static readonly DependencyProperty AltFooProperty = TestControlBase.FooProperty.AddOwner(
        typeof(TestControl),
        new FrameworkPropertyMetadata(67) // New default for this subclass
    );

}


正确重写基类属性的方法是:

The correct way to override a base class's property is:

static TestControl() {

    FooProperty.OverrideMetadata(
        typeof(TestControl),
        new FrameworkPropertyMetadata(67)
    );
}

编辑:

AddOwner 用于在不相关的类型(即)之间共享相同的 DependencyProperty TextBox TextBlock )的TextProperty

AddOwner is meant to share the same DependencyProperty across types that are not related (i.e. the TextProperty of TextBox and TextBlock).