要序列化一個不可序列化的屬性,最好使用可序列化的助手屬性並在兩者之間進行轉換。您必須編寫代碼將兩個屬性同步到一起,以便在序列化時更新它們。這可以通過setter完成。請記住將NonSerialized屬性添加到Brush和任何不可序列化的屬性。
using System;
using System.Runtime.Serialization;
using WindowsMedia = System.Windows.Media;
namespace Something.Something.DarkSide
{
[NonSerialized]
private readonly WindowsMedia.BrushConverter _colorConverter = new WindowsMedia.BrushConverter();
[Serializable]
[DataContract]
public class ClassName: SerializeableBase<ClassName>
{
[DataMember(Name = "ColorString")]
private string _colorString;
public string ColorString
{
get { return _colorString; }
set
{
_colorString = value;
_color = (WindowsMedia.Brush)_colorConverter.ConvertFrom(value);
OnPropertyChanged();
}
}
// Color
[NonSerialized]
private WindowsMedia.Brush _color = WindowsMedia.Brushes.Yellow;
public WindowsMedia.Brush Color
{
get { return _color; }
set
{
_color = value;
_colorString = _colorConverter.ConvertToString(value);
OnPropertyChanged();
}
}
// This triggered when deserializing.
// When deserializing we will have the _color property as null since
// nothing is setting it.
// This ensures we initialize the _color when deserializing from the ColorString property.
[OnDeserialized]
private void SetValuesOnDeserialized(StreamingContext context)
{
_colorConverter = new WindowsMedia.BrushConverter();
_color = (WindowsMedia.Brush)_colorConverter.ConvertFrom(ColorString);
}
public Annotation(string colorHexValue = null)
{
var colorBrush = (WindowsMedia.Brush)_colorConverter.ConvertFrom(colorHexValue);
Color = colorBrush ?? WindowsMedia.Brushes.Yellow;
}
public Annotation(WindowsMedia.Brush colorBrush = null)
{
Color = colorBrush ?? WindowsMedia.Brushes.Yellow;
}
}
}
*注意:當裝載序列化文件的顏色將是無效和構造將不會被調用。然後,您必須創建對象的新實例並使用加載的屬性重新構造它,以便從ColorString設置Color。您也可以在該類中創建一個幫助器方法,並在該屬性上調用該方法來觸發此更改,但請記住它確實在序列化加載時發生了NOT。
var className = ClassName.LoadFromXmlFile(filePath);
// We use the ColorString property because that's what we get after loading
// the serialized file. The Color will be null at this point.
className = new ClassName(className.ColorString);
我有一個小問題試圖加載回來,所以我用這個:
public static SerializableType LoadFromXmlFile(string filename)
{
using (var stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, 1024))
{
using (var reader = XmlDictionaryReader.Create(stream))
{
var serializer = new DataContractSerializer(typeof(SerializableType));
return (SerializableType)serializer.ReadObject(reader);
}
}
}
看到這個http://stackoverflow.com/questions/4488476/how-can-i- serialize-xaml-brush – eYe 2015-04-06 13:31:07
看到了這個解決方案,但它沒有提到如何與其他屬性一起工作?我仍在研究它。謝謝。 – AzzamAziz 2015-04-06 13:32:25
使用BrushConverter類,以便可以將其序列化爲字符串。 – 2015-04-06 13:56:38