用例:用户进行自定义的字体,以在设计图面上的对象,我需要加载/保存到我的数据存储。即像粗体,斜体,大小设置,字体名称必须坚持。
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.
有一些简单(可靠)机制转换/读取字符串重新字体对象的presentation回(在这种情况下,我只需要一个属性)?或者是多个属性结合自定义逻辑正确的选择?
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?
使用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
如果你想使用XML序列化,你可以创建字体类包装,将存储字体属性的某个子集。
If you want to use XML serialization you can create Font class wrapper which will store some subset of Font properties.
注(Gishu) - 不要直接访问类型转换器。相反,通过使用TypeDescriptor访问相应的转换器。非常重要的:)的