我对如何设置自定义控件的依赖属性有点困惑。
我创建了自定义控件,因此它派生自 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/