简体   繁体   English

当null时,在属性上设置默认值

[英]Set default value on properties when null

I'm trying to define a way to set default value on my properties in C#. 我正在尝试定义一种在C#中为我的属性设置默认值的方法。

I have many elements TextBox and a button to restore default value. 我有许多元素TextBox和一个恢复默认值的按钮。 I want that when user click on button, the content for TextBox is set to default. 我希望当用户单击按钮时,TextBox的内容设置为默认值。

My idea is to set value to null and in setter, check value and if value is null, set default. 我的想法是将value设置为null并在setter中检查值,如果value为null,则设置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的示例:

<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. default(ExamplePropertie)不是这样做的好方法。 How can I set value defined with [DefaultValue(value)] ? 如何设置[DefaultValue(value)]定义的[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: 好吧,您可以使用反射来获取该属性的值,但更简单的方法是将默认值存储为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. [DefaultValue(...)]是一个属性。 You cannot get its value by applying default(...) to the name of your property. 通过将default(...)应用于您的属性名称,您无法获得其价值。 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. 该过程更复杂:您需要获取PropertyInfo对象,查询其类型为DefaultValueAttribute的自定义属性,然后才从中获取值。

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: 注意: SetDefault foreach循环可以简化为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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