views:

404

answers:

3

Usecase: The user makes font customizations to an object on the design surface, that I need to load/save to my datastore. I.e. settings like Bold, Italics, Size, Font Name need to persisted.

Is there some easy (and reliable) mechanism to convert/read back from a string representation of the font object (in which case I would need just one attribute)? Or is multiple properties combined with custom logic the right option?

+8  A: 

Use TypeConverter:

Font font = new Font("Arial", 12, GraphicsUnit.Pixel);

TypeConverter converter = TypeDescriptor.GetConverter(typeof (Font));

string fontStr = converter.ConvertToInvariantString(font);

Font font2 = (Font) converter.ConvertFromString(fontStr);

Console.WriteLine(font.Name == font2.Name); // prints True

If you want to use XML serialization you can create Font class wrapper which will store some subset of Font properties.

Note(Gishu) - Never access a type converter directly. Instead, access the appropriate converter by using TypeDescriptor. Very important :)

aku
Great!.. works as advertised - Thanks aku. Voting you closer to the 5K mark :)
Gishu
I'm glad I managed to help you, thanks for voting :)
aku
A: 

What type of datastore do you need to persist this in? If it is just user settings that can be persisted in a file you could serialise the font object to a settings file in either binary or xml (if you want to be able to edit the config file directly). The serialisation namespaces (System.Xml.Serialization and System.Runtime.Serialization) provide all the tools to do this without writing custom code.

MSDN Site on XML Serialisation: XML Serialization in the .Net Framework

[EDIT]So aparrently the font object isn't serialisable. oops :( Sorry.

Dr8k
Font object is not serializable.
aku
A: 

In the project I'm working on, I went with the multiple properties.

I save the font to a database table by breaking out its name, size, style and unit and then persist those values.

Recreating the font on demand once these values are retrived is a snap.

absfabs