我正在尝试定义一种在 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/