c# - 自定义控件的 WPF 依赖属性

标签 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 的依赖属性?

最佳答案

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:

不,不应该。 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); }
    }
}

关于c# - 自定义控件的 WPF 依赖属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1851598/

相关文章:

c# - 访问 IEnumerable 的属性

wpf - 使用 MatrixTransform 平滑动画?

c# - 绑定(bind)数据网格列宽

WPF自定义绘制多个进度条

jsf - 自定义 JSF 组件属性列表

ios - 以编程方式选择选项卡自定义选项卡栏ios

c# - 如何从域模型中的内部服务类通知进度

c# - 如何通过 Fluent API Entity Framework 定义多对多关系?

c# - 将 Foreach 分成线程示例

wpf 生成不需要的 wisptis.exe