Kliver Max
Kliver Max

Reputation: 5299

How to create custom properties in user control?

I have a user control with two fields:

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

After added this control in my form and fill OffText and OnText properties. In control's constructor i have:

    public FakeToggleSwitch()
    {
        InitializeComponent();

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

And in debug mode i see that OnText and OffText are null. Whats can be wrong here? What have to i make with fields?

Upvotes: 0

Views: 74

Answers (1)

Sinatr
Sinatr

Reputation: 21969

Those are not fields, but auto-properties.

If you use auto-property and its default value should be different from 0 (value type) or null (reference type), then you can set it in the constructor

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

public Constructor()
{
    // init
    OffText = "...";
    OnText = "...";
}

Otherwise you may decide to use normal properties

private string _offText = "..."; // default value
public string OffText
{
    get { return _offText; }
    set { _offText = value; }
}

If you use wpf, then typically UserControl properties there have to be dependency properties (to support binding). Creating dependency property is easily done by using code snippets. Type

propdp TabTab

to get

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));

Upvotes: 1

Related Questions