6

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?

3 Answers 3

10

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 :)

2
  • Great!.. works as advertised - Thanks aku. Voting you closer to the 5K mark :)
    – Gishu
    Sep 23, 2008 at 8:55
  • 1
    I think that ConvertFromInvariantString() should be used as counterpart of ConvertToInvariantString() (instead of ConvertFromString() seen in the above example).
    – miroxlav
    May 12, 2015 at 19:58
0

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.

-1

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.

1
  • Font object is not serializable.
    – aku
    Sep 23, 2008 at 2:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.