Cannot Serialize SolidColorBrush

99封情书 提交于 2020-01-14 02:39:33

问题


Error message that I cannot serialize a class because cannot serialize SolidColorBrush

The class has a public property of Brush

Is there a fix?

It is more complex.
I tried using a backing property that can be serialized
Problem is that I also need to Freeze the HighLight so I can be created on a BackgroundWorker
If I use a serializable backing property for HighLight then Highlight.Freeze fails

[Serializable()]
public class WordIdLenHightlight : Object
{
    private string highlightHex;
    public Int32 ID { get; private set; }
    public Byte Len { get; private set; }
    //[NonSerialized]
    public Brush Highlight { get;  private set; }
    //{ if (string.IsNullOrEmpty(highlightHex)) return null; else return new SolidColorBrush((Color)ColorConverter.ConvertFromString(highlightHex)); }
    public string HighlightHex { get { return highlightHex; } }
    public override bool Equals(Object obj)
    {
        // Check for null values and compare run-time types.
        if (obj == null) return false;
        if (!(obj is WordIdLenHightlight)) return false;
        WordIdLenHightlight comp = (WordIdLenHightlight)obj;
        return (comp.ID == this.ID);
    }
    public override int GetHashCode()
    {
        return ID;
    }
    public WordIdLenHightlight(WordIdLenHightlight w) 
    { 
        ID = w.ID; Len = w.Len; 
        Highlight = w.Highlight;
        highlightHex = w.Highlight.ToString();
        Highlight.Freeze(); 
    }
    public WordIdLenHightlight(Int32 id, byte len, Brush highlight) 
    { 
        ID = id; Len = len; 
        Highlight = highlight; 
        //highlightHex = Highlight.ToString();
        Highlight.Freeze(); 
    }
    public WordIdLenHightlight(Int32 id, byte len, string HighlightHex) 
    {
        highlightHex = HighlightHex;
        ID = id; 
        Len = len;
        Highlight = new SolidColorBrush((Color)ColorConverter.ConvertFromString(highlightHex));
        Highlight.Freeze();
    }
}

回答1:


You don't say how you're serializing the class, but you can probably decorate the Brush property or its backing field by an attribute such as NonSerialized or XmlIgnore.

You might want to serialize some other information than enables you to reconstruct the Brush on deserialization, for example, its color.



来源:https://stackoverflow.com/questions/20251564/cannot-serialize-solidcolorbrush

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!