简体   繁体   中英

Set default value on properties when null

I'm trying to define a way to set default value on my properties in C#.

I have many elements TextBox and a button to restore default value. I want that when user click on button, the content for TextBox is set to default.

My idea is to set value to null and in setter, check value and if value is null, set default.

There is my code :

private void SetDefault()
{
    Grid actualItem = tabControl.SelectedContent as Grid;
    if (actualItem != null)
    {
        foreach (object elt in actualItem.Children)
        {
            if (elt.GetType() == typeof(TextBox))
            {
                TextBox box = elt as TextBox;
                box.Text = null;
            }
        }
    }
}

example of TextBox:

<TextBox Grid.Row="1" Grid.Column="1"
         Style="{StaticResource TextBoxStyle}"
         Text="{Binding ExamplePropertie,
                Mode=TwoWay,
                UpdateSourceTrigger=PropertyChanged}"/>

For each binded element I wanted to do something like this :

[DefaultValue("default")]
public String ExamplePropertie
{
    get
    {
        return _myProp;
    }
    set
    {
        if (value == null)
            default(ExamplePropertie); // Not working
        else
            _myProp = value;
        OnPropertyChanged(nameof(ExamplePropertie));
    }
}

But default(ExamplePropertie) is not the good way to do that. How can I set value defined with [DefaultValue(value)] ?

Well, you can resort to reflection to obtain the value of that attribute but a simpler way would be to simply store the default value as a const:

private const string ExamplePropertieDefault = "default";

[DefaultValue(ExamplePropertieDefault)]
public String ExamplePropertie
{
    get
    {
        return _myProp;
    }
    set
    {
        if (value == null)
            ExamplePropertieDefault;
        else
            _myProp = value;
        OnPropertyChanged(nameof(ExamplePropertie));
    }
}

[DefaultValue(...)] is an attribute. You cannot get its value by applying default(...) to the name of your property. The process is more complicated: you need to get PropertyInfo object for your property, query it for a custom attribute of type DefaultValueAttribute , and only then grab the value from it.

The process goes much easier with a helper method:

static T GetDefaultValue<T>(object obj, string propertyName) {
    if (obj == null) return default(T);
    var prop = obj.GetType().GetProperty(propertyName);
    if (prop == null) return default(T);
    var attr = prop.GetCustomAttributes(typeof(DefaultValueAttribute), true);
    if (attr.Length != 1) return default(T);
    return (T)((DefaultValueAttribute)attr[0]).Value;
}

Put this helper method into a separate class, and use it as follows:

_myProp = value ?? Helper.GetDefaultValue<string>(this, nameof(ExampleProperty));

Note: foreach loop in SetDefault can be simplified like this:

foreach (object box in actualItem.Children.OfType<TextBox>()) {
    box.Text = null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM