开发者

WPF Dependency Property for Custom Control

I'm a bit in a mess with how to set a Dependency Property for Custom Co开发者_如何学JAVAntrol.

I created Custom Control, so it derives from Control class.

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

In order to set Dependency Property I have to register it inside a class which must be derived from DependencyObject. So it should be another class:

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

How now I could set MyFirst property as dependency property for CustControl?


In order to set Dependency Property I have to register it inside a class which must be derived from DependencyObject. So it should be another class:

No, it shouldn't. Control already derives from DependencyObject. Since inheritance is transitive, this makes CustControl a subtype of DependencyObject as well. Just put it all into 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); }
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜