我对如何为自定义控件设置依赖项属性感到困惑。

我创建了自定义控件,因此它派生自Control类。

public class CustControl : Control
    {
      static CustControl()
       {
         DefaultStyleKeyProperty.OverrideMetadata(typeof(CustControl), new FrameworkPropertyMetadata(typeof(CustControl)));
       }
    }


为了设置Dependency Property,我必须在必须从DependencyObject派生的类中注册它。所以应该是另一类:

class CustClass : DependencyObject
{
    public readonly static DependencyProperty MyFirstProperty = DependencyProperty.Register("MyFirst", typeof(string), typeof(CustControl), new PropertyMetadata(""));

    public string MyFirst
    {
        get { return (string)GetValue(MyFirstProperty); }
        set { SetValue(MyFirstProperty, value); }
    }
}


现在如何将MyFirst属性设置为CustControl的依赖项属性?

最佳答案

为了设置Dependency Property,我必须在必须从DependencyObject派生的类中注册它。所以应该是另一类:


不,不应该。 Control已经从DependencyObject派生。因为继承是transitive,所以这也使CustControl成为DependencyObject的子类型。只需将其全部放入CustControl

public class CustControl : Control
{
      static CustControl()
      {
          DefaultStyleKeyProperty.OverrideMetadata(typeof(CustControl), new FrameworkPropertyMetadata(typeof(CustControl)));
      }

    public readonly static DependencyProperty MyFirstProperty = DependencyProperty.Register("MyFirst", typeof(string), typeof(CustControl), new PropertyMetadata(""));

    public string MyFirst
    {
        get { return (string)GetValue(MyFirstProperty); }
        set { SetValue(MyFirstProperty, value); }
    }
}

10-05 23:51