1
votes

I have one class and i set [Serializable] and define one FontFamily class to that class.But when I am trying to serialize it gives me an error like "Additional information: Type 'System.Windows.Media.FontFamily' in Assembly 'PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' is not marked as serializable."

1

1 Answers

3
votes

You will have to implement serialization yourself for these fields, i.e., you will need Custom Serialization. On approach to do that is as follows:

  1. Mark the non-serializable fields with the [NonSerialized] attribute.

  2. Add a new temporary field with a serializable type, e.g. private string _fontFamilySerialized;

  3. Add three methods to your class, marked with the [OnSerializing], [OnSerialized] and [OnDeserialized] attributes, respectively.

  4. In the OnSerializing method, serialize the value of your font family into the temporary field (e.g., by extracting the name of the font family).

  5. In the OnSerialized method, clear the temporary field - it's no longer needed, and we don't want people to start using it.

  6. In the OnDeserialized method, deserialize the value from the temporary field to your font family field (e.g., by creating a new FontFamily object based on the name stored in the temporary field).