gpt4 book ai didi

c# - 使用 `DataContractSerializer` 序列化包含 WPF 画笔的类

转载 作者:太空宇宙 更新时间:2023-11-03 21:19:58 25 4
gpt4 key购买 nike

我有一个正在序列化的类:

using (FileStream fileStreamWriter = new FileStream(fileName, FileMode.Create))
{
var dataContractSerializer = new DataContractSerializer(typeof(ClassToBeSerialized));
dataContractSerializer.WriteObject(fileStreamWriter, btChartGroupList);
fileStreamWriter.Close();
}

在我添加 Brush 类型的属性之前,这一切正常(称为 AreaBrush)到 ClassToBeSerialized 类。此 AreaBrush 属性可以是 SolidBrushLinearGradientBrushRadialGradientBrush。在序列化期间,DataContractSerializer 抛出:

Type 'System.Windows.Media.MatrixTransform' with data contract name 'MatrixTransform:http://schemas.datacontract.org/2004/07/System.Windows.Media' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer.

关于如何让它工作的任何想法?我尝试了 BrushConverter 但运气不佳。

我想我可以添加所有 3 种类型的画笔作为属性,但我希望有更好的解决方案。

编辑:在 VMaleev 的帮助下,我最终做到了:

        [IgnoreDataMember]
public Brush AreaBrush
{
get { return _areaBrush; }
set
{
SetProperty(ref _areaBrush, value, () => AreaBrush);
}
}

[DataMember]
public string AreaBrushText
{
get
{
using (StringWriter sw = new StringWriter())
{
XamlWriter.Save(AreaBrush, sw);
string s = sw.ToString();
return sw.ToString();
}
}
set
{
AreaBrush = (Brush)XamlReader.Parse(value);
}
}

最佳答案

你不能简单地做到这一点。我建议您将 Brush 属性标记为 [XmlIgnore] 并使用 XamlWriter 分别对其进行序列化和反序列化。和 XamlReader :

// example of writing
using (var outfile = File.CreateText("Brush.xaml"))
{
XamlWriter.Save(brush, outfile);
}

// example of reading
using (Stream s = File.OpenRead("Brush.xaml"))
{
Brush b = XamlReader.Load(s);
}

查看this更多信息的主题

关于c# - 使用 `DataContractSerializer` 序列化包含 WPF 画笔的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31465534/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com