【问题标题】:Where to initialize reference type dependency properties for a custom control?在哪里初始化自定义控件的引用类型依赖属性?
【发布时间】:2015-11-06 01:42:39
【问题描述】:

我有一个带有依赖属性的自定义控件。我知道如果依赖属性是引用类型,我需要在控件的每个实例中初始化它,否则它们都使用相同的对象。在普通控件中,我在构造函数中执行此操作。但是在我的自定义控件中,我在哪里执行此操作? OnApplyTemplate() 方法?

【问题讨论】:

  • 你有代码示例吗?

标签: c# wpf


【解决方案1】:

DependencyProperty 可以像在任何声明DependencyProperty 的类中一样以传统方式创建。在CustomControl中声明依赖属性没有特殊规则。

public class YourCustomControl : Control
{
    public static readonly DependencyProperty TestPropProperty =
        DependencyProperty.Register("TestProp", typeof(string), typeof(TestControl), new UIPropertyMetadata(null));

    public string TestProp
    {
        get { return (string)GetValue(TestPropProperty); }
        set { SetValue(TestPropProperty, value); }
    }

    static YourCustomControl()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(TestControl), new FrameworkPropertyMetadata(typeof(TestControl)));
    }
}

【讨论】:

    【解决方案2】:

    看起来这是解决方案:http://www.thomasclaudiushuber.com/blog/2010/02/11/be-careful-with-default-values-of-dependency-properties-if-youre-using-reference-types/

    您可以为自定义控件同时使用静态构造函数和实例构造函数。在实例构造函数中初始化引用类型依赖属性。

    【讨论】:

    • 构造函数总是初始化属性和值类型,即使你没有像我的回答那样在构造函数中写你的属性或值类型:)
    猜你喜欢
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 2011-12-21
    • 1970-01-01
    相关资源
    最近更新 更多