Skip to main content
 首页 » 编程设计

wpf之如何更改继承的依赖属性的默认值

2024年12月31日13tintown

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

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

这是我目前为实现这一目标所做的工作(例如,这是一个带有 'Foo' DP 的测试控件。)尽管感谢 AddOwner,但我不喜欢隐藏属性的"new"功能。 ,它确实指向同一个共享实例,所以我想这没问题。看起来它也继承了所有其他元数据值,所以很好。只是想知道这是否正确?

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

标记

更新...

我认为这更好,因为它消除了"new"调用。您仍然可以通过基类上的 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 
    ); 
 
} 

请您参考如下方法:

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

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

编辑:
AddOwner旨在共享相同的 DependencyProperty跨不相关的类型(即 TextPropertyTextBoxTextBlock )。