I have the class CaptureResolution
representing the resolution for a camera capture:
[Serializable]
[SettingsSerializeAs(SettingsSerializeAs.Xml)]
[XmlRoot (ElementName = "CaptureResolution", IsNullable = false)]
public class CaptureResolution: ApplicationSettingsBase
{
[UserScopedSetting]
[SettingsSerializeAs(SettingsSerializeAs.Xml)]
[XmlAttribute (AttributeName = "Width")]
public int Width { get; set; }
[UserScopedSetting]
[SettingsSerializeAs(SettingsSerializeAs.Xml)]
[XmlAttribute(AttributeName = "Height")]
public int Height { get; set; }
public CaptureResolution(int width, int height)
{
Width = width;
Height = height;
}
public CaptureResolution(): this(1024, 720)
{
}
}
I added a setting into the settings designer with the given type:
However when calling this
Properties.Settings.Default.ResolutionSelection = new CaptureResolution(1920, 1080);
Properties.Settings.Default.Save();
The setting is not saved in the user settings file:
<setting name="ResolutionSelection" serializeAs="Xml">
<value />
</setting>
I can surely verify that the value is assigned to the setting's property. Otherwise the program wouldn't work at all. I also had a look with the debugger on this.
Also I already searched on the internet for suitable solutions but in the end it didn't really helped. Other settings are saved without any problems.
Afaik the settings designer needs a class that can be serialized to XML and a default parameterless constructor that is public accessible. I did both so I'm wondering why it is not working as intended.
Additional question
How can I assign a default value to this custom type setting?
Entering new FaceDetection.Model.CaptureResolution()
ends up in an exception.
You are deriving CaptureResolution
from ApplicationSettingsBase
:
public class CaptureResolution: ApplicationSettingsBase
Don't do that. There is no need to do it, and doing so obviously doesn't work.
Default Value
The settings desinger will create a Settings.cs
if you click on the "View Code" button on its top. In this Settings.cs
file you can add your own code and you can manually create application settings, e.g. something like that:
[UserScopedSetting]
public CaptureResolution ResolutionSelection
{
get
{
var value = (CaptureResolution)this[nameof(ResolutionSelection)];
if (value == null)
{
value = new CaptureResolution(1, 2); // decent default value
this[nameof(ResolutionSelection)] = value;
}
return value;
}
set { this[nameof(ResolutionSelection)] = value; }
}
This will create a default value it the setting is null. You will have to remove the setting that you created using the desinger.