如何XMLSERIALIZE System.Drawing.Font类 [英] How to XmlSerialize System.Drawing.Font class

查看:132
本文介绍了如何XMLSERIALIZE System.Drawing.Font类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

System.Drawing.Font 不是XML序列化,因为它没有一个默认的(空的)构造函数。
有一些变通或序列化字体不过?

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 serialize Font nevertheless?

推荐答案

编辑:我更新根据code <一个href="http://stackoverflow.com/questions/1940127/how-to-xmlserialize-system-drawing-font-class/1940307#1940307">Regent建议使用 FontConverter ,而preserving能够使用的 SerializableFont 定期字体

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;
    }
}

用法:当你有一个字体属性,它声明为 SerializableFont 。这将允许它被序列化,而隐式转换将处理转换为你。

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.

Font MyFont {get;set;}

写:

SerializableFont MyFont {get;set;}

这篇关于如何XMLSERIALIZE System.Drawing.Font类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆