c# - 在 null 时设置属性的默认值

标签 c# default-value

我正在尝试定义一种在 C# 中为我的属性设置默认值的方法。

我有很多元素 TextBox 和一个按钮来恢复默认值。我希望当用户单击按钮时,TextBox 的内容设置为默认值。

我的想法是将值设置为 null 并在 setter 中检查值,如果值为 null,则设置默认值。

这是我的代码:

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

文本框示例:

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

对于每个绑定(bind)元素,我想做这样的事情:

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

但是 default(ExamplePropertie) 并不是这样做的好方法。如何设置用 [DefaultValue(value)] 定义的值?

最佳答案

好吧,您可以求助于反射来获取该属性的值,但更简单的方法是将默认值简单地存储为常量:

private const string ExamplePropertieDefault = "default";

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

关于c# - 在 null 时设置属性的默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39037153/

相关文章:

c# - async-await 的不同行为

c# - 将编辑的 html 文件保存到特定文件夹

C# 声明同一个表的多个实例

java - 具有多重性的 EByteArray 或 EFloat 的 Ecore defaultValue

c# - 如何在不占用大量内存的情况下显示图像

c# - 我如何在 MVC 中实现两个 Controller

c++ - 在 C++ 的链接列表方法中,如何将参数默认为其最后一个索引?

C# 字符串比较器 : Optional Argument Default

c++ - 如何通过未定义类型定义元函数?