Search code examples
c#xmlwindows-phonexml-serializationisolatedstorage

Serialize FontFamily in Windows Phone


I'm trying to read/save a xml-file in my windows phone application with the XmlSerializer. Unfortunately I can't read/write it because I'm using the FontFamily in my class:

public class Article
{
    public string name { get; set; }
    private FontFamily _fontitem;
    public FontFamily FontItem
    {
        get
        {
            return _fontitem;
        }
        set
        {
            _fontitem = value;
            RaisePropertyChanged(() => FontItem);
        }
    }
}

I'm using a class named StorageHelper just like here: http://blogs.msdn.com/b/dawate/archive/2010/08/31/windows-phone-7-xml-isolatedstorage-example.aspx Instead of the class "Jog" I use my class "Article".

When I try to load/save the xml this error comes up: "fontfamily cannot be serialized because it does not have a paramterless constructor"


Solution

  • In this case, you can create a FontFamily from its name. Therefore you can modify your Article class to be like this:

    [Serializable]
    public class Article
    {
        private string _fontItemString;
    
        public string Name { get; set; }
    
        [XmlIgnore]
        public FontFamily FontItem
        {
            get
            {
                return new FontFamily(FontItemString);
            }
        }
    
        public string FontItemString
        {
            get { return _fontItemString; }
            set
            {
                _fontItemString = value;
                RaisePropertyChanged(() => FontItem);
            }
        }
    }
    

    This way you don't serialize the FontFamily object itself, but serialize the name of the font family to use. Whenever the font family string changes, you can notify the actual FontItem was changed, and then initialize the FontFamily from FontItemString