我正在尝试定义一种方法来在C#中设置我的属性的默认值。
我有许多元素TextBox和一个按钮来恢复默认值。我希望当用户单击按钮时,TextBox的内容设置为默认值。
我的想法是将值设置为空,在setter中,检查值,如果值为空,则设置默认值。
这是我的密码:
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的例子:
<TextBox Grid.Row="1" Grid.Column="1"
Style="{StaticResource TextBoxStyle}"
Text="{Binding ExamplePropertie,
Mode=TwoWay,
UpdateSourceTrigger=PropertyChanged}"/>对于每个绑定元素,我都想这样做:
[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)]定义的值?
发布于 2016-08-19 11:06:31
[DefaultValue(...)]是一个属性。不能通过将default(...)应用于属性的名称来获取其值。这个过程更复杂:您需要为您的属性获取PropertyInfo对象,查询它以获得DefaultValueAttribute类型的自定义属性,然后从它获取值。
使用助手方法,这个过程要简单得多:
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;
}将此助手方法放入单独的类中,并按以下方式使用:
_myProp = value ?? Helper.GetDefaultValue<string>(this, nameof(ExampleProperty));注意: foreach循环在SetDefault中可以简化如下:
foreach (object box in actualItem.Children.OfType<TextBox>()) {
box.Text = null;
}发布于 2016-08-19 10:54:35
那么,您可以求助于反射来获取该属性的值,但更简单的方法是将默认值存储为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));
}
}https://stackoverflow.com/questions/39037153
复制相似问题