.NET Application Settings: Make an array of Color values
Usually you can make an array in the application settings by changing the data type manually in the code. However, System.Drawing.Color seems to be an exception. You can add it in the code as usually, and it even lets you edit the values in the graphical editor like other settings. It seems there is a problem serializing the data though, as it is subsequently lost.
I then looked for methods in the code thinking the editor had got a bug in it somewhere, so tried this in the settings file:
<Setting Name="ChannelColour" Type="System.Drawing.Color[]" Scope="User">
<Value Profile="(Default)"><?xml version="1.0" encoding="utf-16"?>
<ArrayOf开发者_如何学GoColor xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<color>Cyan</color>
<color>DarkOrange</color>
<color>Magenta</color>
<color>LawnGreen</color>
</ArrayOfColor>
</Value>
</Setting>
And likewise in app.config:
<setting name="ChannelColour" serializeAs="Xml">
<value>
<ArrayOfColor xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<color>Cyan</color>
<color>DarkOrange</color>
<color>Magenta</color>
<color>LawnGreen</color>
</ArrayOfColor>
</value>
</setting>
I then didn't touch the editor and made sure any existing config files where gone. It still didn't work.
Why is it that other arrays work fine, and Color values on their own are one of the default options, yet the combination doesn't work at all?
In the end I did it like this:
First I added a class called ColorCollection
which was basically a wrapper around Color[]
with only one main difference (event handling).
Added a property to the Settings class for a ColorCollection and then stored the settings as a StringCollection that I manually set using the Settings loading and saving event handlers using methods I added/overloaded in ColorCollection
(ToString
and Parse
).
Because changing and array subscript doesn't trigger the PropertyChanged
event, I then added a new event called Changed
that could be invoked by other classes (PropertyChanged
is defined in another class so we can't manually invoke it even from within the Settings
class. I then added the event trigger to the set
statement.
It's messy, but at least there is some level of abstraction so the messiness isn't instantly visible. I ended up doing something similar for most arrays I needed in settings as I needed the events to be triggered if a subscript changed.
精彩评论