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 的依赖属性?
为了设置依赖属性,我必须在必须从 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)
归档时间: |
|
查看次数: |
6684 次 |
最近记录: |