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)] ?
constvalue alongside your property and use it in both the attribute and the code in the setter.default(ExamplePropertie)just gets the default value of thattypewhich is alwaysnullfor any reference type. TheDefaultValueattribute is unrelated to that.