Custom SettingsProvider and retrieving default value
I have implemented my own class that inherits from the SettingsProvider class. If the value I am retrieving has not been set by the use开发者_开发问答r, i.e. it is the first time the program starts, I attempt to grab the default value. The problem I am seeing is when the default value is retrieved from the SettingsProperty it comes back as a string. I have tried to add some code that converts the item but I am running into problems when converting System.Drawing.Colors and am receiving the error "Invalid cast from 'System.String' to 'System.Drawing.Color'.".
Here is an example of the code I am using to get the default value:
private object GetDefaultValue(SettingsProperty setting)
{
if (setting.PropertyType.IsEnum)
return Enum.Parse(setting.PropertyType, setting.DefaultValue.ToString());
// Return the default value if it is set
if (setting.DefaultValue != null)
return Convert.ChangeType(setting.DefaultValue, setting.PropertyType);
else // If there is no default value return the default object
return Activator.CreateInstance(setting.PropertyType);
}
How can I properly convert the default value to the correct type?
Ok. So I found the answer. Instead of using Convert.ChangeType you need to actually create a TypeConverter instance against the settings.PropertyType. This code Works:
private object GetDefaultValue(SettingsProperty setting)
{
if (setting.PropertyType.IsEnum)
return Enum.Parse(setting.PropertyType, setting.DefaultValue.ToString());
// Return the default value if it is set
// Return the default value if it is set
if (setting.DefaultValue != null)
{
System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(setting.PropertyType);
return tc.ConvertFromString(setting.DefaultValue.ToString());
}
else // If there is no default value return the default object
{
return Activator.CreateInstance(setting.PropertyType);
}
}
精彩评论