【问题标题】:WPF Dependency Property for Custom Control自定义控件的 WPF 依赖属性
【发布时间】:2009-12-05 08:41:24
【问题描述】:

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

我创建了自定义控件,因此它派生自 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 的依赖属性?

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-27
      • 1970-01-01
      • 2012-08-07
      • 2012-08-29
      • 1970-01-01
      相关资源
      最近更新 更多