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

Mar*_*eIV 23 wpf dependency-properties subclass default-value

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

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

以下是我目前正在做的事情(这是一个带有'Foo'DP的测试控件的例子.)我不是隐藏属性的'新'的粉丝虽然感谢AddOwner,但它确实指出了到同一个共享实例所以我猜它没关系.它看起来像是继承了所有其他元数据值,所以这很好.只是想知道这是否正确?

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
    );

}
Run Code Online (Sandbox Code Playgroud)

标记

更新中...

我认为这更好,因为它消除了"新"呼叫.您仍然可以通过基类上的FooProperty访问它,因为它使用了AddOwner.因此,它在技术上是相同的.

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
    );

}
Run Code Online (Sandbox Code Playgroud)

Cod*_*ked 40

覆盖基类属性的正确方法是:

static TestControl() {

    FooProperty.OverrideMetadata(
        typeof(TestControl),
        new FrameworkPropertyMetadata(67)
    );
}
Run Code Online (Sandbox Code Playgroud)

编辑:

AddOwner意味着DependencyProperty在不相关的类型(即TextPropertyof TextBoxTextBlock)之间共享相同的内容.

  • @MarqueIV - 查看反射器中的代码,您无需再次设置它们.将多个设置进行OR运算(即,如果基本设置AffectsRender或您设置AffectsRender,则它会影响渲染),其他设置可以被覆盖(例如Inherits). (2认同)