The classSystem.Drawing.Font
is not XML Serializable since it doesn\'t have a default (empty) constructor.
Is there some work around or alternative way to
Edit: I updated the code according to Regent suggestion to use FontConverter
, while preserving the ability to use the SerializableFont
as regular Font
.
public class SerializableFont
{
public SerializableFont()
{
FontValue = null;
}
public SerializableFont(Font font)
{
FontValue = font;
}
[XmlIgnore]
public Font FontValue { get; set; }
[XmlElement("FontValue")]
public string SerializeFontAttribute
{
get
{
return FontXmlConverter.ConvertToString(FontValue);
}
set
{
FontValue = FontXmlConverter.ConvertToFont(value);
}
}
public static implicit operator Font(SerializableFont serializeableFont)
{
if (serializeableFont == null )
return null;
return serializeableFont.FontValue;
}
public static implicit operator SerializableFont(Font font)
{
return new SerializableFont(font);
}
}
public static class FontXmlConverter
{
public static string ConvertToString(Font font)
{
try
{
if (font != null)
{
TypeConverter converter = TypeDescriptor.GetConverter(typeof(Font));
return converter.ConvertToString(font);
}
else
return null;
}
catch { System.Diagnostics.Debug.WriteLine("Unable to convert"); }
return null;
}
public static Font ConvertToFont(string fontString)
{
try
{
TypeConverter converter = TypeDescriptor.GetConverter(typeof(Font));
return (Font)converter.ConvertFromString(fontString);
}
catch { System.Diagnostics.Debug.WriteLine("Unable to convert"); }
return null;
}
}
Usage: When you have a Font
property, declare it as SerializableFont
. This will allow it to be serialized, while the implicit cast will handle the conversion for you.
Instead of writing:
Font MyFont {get;set;}
Write:
SerializableFont MyFont {get;set;}