自定义控件的 WPF 依赖属性

rem*_*rem 2 c# wpf dependency-properties custom-controls

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

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

public class CustControl : Control 
    {
      static CustControl()
       {
         DefaultStyleKeyProperty.OverrideMetadata(typeof(CustControl), new FrameworkPropertyMetadata(typeof(CustControl)));       
       }        
    }
Run Code Online (Sandbox Code Playgroud)

为了设置依赖属性,我必须在必须从 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); }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Hei*_*nzi 5

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

不,不应该。Control已经从DependencyObject. 由于继承是可传递的,这也是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); }
    }
}
Run Code Online (Sandbox Code Playgroud)