[英]How to create custom properties in user control?
我有两个字段的用户控件:
public string OffText { set; get; }
public string OnText { set; get; }
在我的表单中添加此控件并填充OffText
和OnText
属性之后。 在控件的构造函数中,我有:
public FakeToggleSwitch()
{
InitializeComponent();
if (State)
{
CheckEdit.Text = OnText;
}
else
{
CheckEdit.Text = OffText;
}
}
在调试模式下,我看到OnText
和OffText
为null
。 这里有什么问题吗? 我必须对字段做些什么?
这些不是字段,而是auto-properties 。
如果使用自动属性,并且其默认值应不同于0
(值类型)或null
(引用类型),则可以在构造函数中进行设置
public string OffText { set; get; }
public string OnText { set; get; }
public Constructor()
{
// init
OffText = "...";
OnText = "...";
}
否则,您可能会决定使用常规属性
private string _offText = "..."; // default value
public string OffText
{
get { return _offText; }
set { _offText = value; }
}
如果使用wpf
,则通常UserControl
属性必须具有依赖项属性(以支持绑定)。 使用代码片段可以轻松创建依赖项属性。 类型
propdp 选项 卡
要得到
public int MyProperty
{
get { return (int)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}
// Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(int), typeof(ownerclass), new PropertyMetadata(0));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.