如何在用户控件中创建自定义属性?

时间:2014-10-07 11:06:05

标签: c# user-controls

我有一个包含两个字段的用户控件:

public string OffText { set; get; }
public string OnText { set; get; }

在我的表单中添加此控件并填写OffTextOnText属性。在控件的构造函数中,我有:

    public FakeToggleSwitch()
    {
        InitializeComponent();

        if (State)
        {
            CheckEdit.Text = OnText;
        }
        else
        {
            CheckEdit.Text = OffText;
        }
    }

在调试模式下,我看到OnTextOffTextnull。这可能是错的?我用田地做了什么?

1 个答案:

答案 0 :(得分:1)

这些不是字段,而是auto-properties

如果您使用auto-property且其默认值应不同于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属性必须有依赖属性(以支持绑定)。使用code snippets可以轻松创建依赖项属性。型

  

propdp Tab Tab

获取

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));
相关问题