自定义控件的WPF依赖属性

时间:2009-12-05 08:41:24

标签: c# wpf custom-controls dependency-properties

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

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

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

为了设置依赖属性,我必须在一个必须从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的依赖项属性?

1 个答案:

答案 0 :(得分:4)

  

为了设置依赖属性,我必须在一个必须从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); }
    }
}