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?
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With