gpt4 book ai didi

c# - DataTemplate 序列化期间出现 InvalidOperationException

转载 作者:行者123 更新时间:2023-11-30 18:24:27 26 4
gpt4 key购买 nike

我正在尝试找到一种序列化 DataTemplate 的方法。

ObservableCollection<XMLColumns> xmlColumns = new ObservableCollection<XMLColumns>();
try
{
ReadColumnXMLData(File.ReadAllText(Environment.CurrentDirectory + "lorenzo_columns_test.xml"));
}
catch (Exception)
{
//In Framework
if (xmlColumns.Count == 0)
{
foreach (var item in grdAuft.Columns)
{
XMLColumns col = new XMLColumns();
col.FieldName = item.FieldName;
if (item.CellTemplate != null)
{
col.CellTemplate = item.CellTemplate;
}
if (item.GroupValueTemplate != null)
{
col.GroupValueTemplate = item.GroupValueTemplate;
}
if (item.ActualEditSettings != null)
{
//col.EditSettings = item.ActualEditSettings;
}
xmlColumns.Add(col);
}
string xml = LsgUtil.SerializeCollection(xmlColumns);
File.WriteAllText(Environment.CurrentDirectory + "lorenzo_columns_test.xml",xml);
}
}

Serialize 函数抛出异常,我无法序列化 DataTemplate

数据结构如下:

public class XMLColumns
{
public string FieldName { get; set; }
public DataTemplate CellTemplate { get; set; }
public DataTemplate GroupValueTemplate { get; set; }
//public object EditSettings { get; set; }
}

谢谢

编辑:

异常:InvalidOperationException

堆栈跟踪:

System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModelmodel, String ns, ImportContext context, String dataType,XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiterlimiter)    bei
System.Xml.Serialization.XmlReflectionImporter.ImportElement(TypeModelmodel, XmlRootAttribute root, String defaultNamespace,RecursionLimiter limiter) bei
System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Typetype, XmlRootAttribute root, String defaultNamespace) bei
System.Xml.Serialization.XmlSerializer..ctor(Type type, StringdefaultNamespace) bei
System.Xml.Serialization.XmlSerializer..ctor(Type type) bei
ApplicationBase.LsgUtil.SerializeCollection[T1](ObservableCollection`1coll) bei
LSG_Bau.Views.Auft.AuftView.AuftView_Loaded(Objectsender, RoutedEventArgs e) inc:\Application\App_LSG\LSG_Bau\LSG_Bau\Views\Auft\2_UE\AuftView.xaml.cs:Zeile100. bei
System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs) bei
System.Windows.EventRoute.InvokeHandlersImpl(Object source,RoutedEventArgs args, Boolean reRaised) bei
System.Windows.UIElement.RaiseEventImpl(DependencyObject sender,RoutedEventArgs args) bei
System.Windows.UIElement.RaiseEvent(RoutedEventArgs e) bei
System.Windows.BroadcastEventHelper.BroadcastEvent(DependencyObjectroot, RoutedEvent routedEvent) bei
System.Windows.BroadcastEventHelper.BroadcastLoadedEvent(Object root) bei
MS.Internal.LoadedOrUnloadedOperation.DoWork() bei
System.Windows.Media.MediaContext.FireLoadedPendingCallbacks() bei
System.Windows.Media.MediaContext.FireInvokeOnRenderCallbacks() bei
System.Windows.Media.MediaContext.RenderMessageHandlerCore(ObjectresizedCompositionTarget) bei
System.Windows.Media.MediaContext.AnimatedRenderMessageHandler(ObjectresizedCompositionTarget) bei
System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegatecallback, Object args, Int32 numArgs) bei
MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Objectsource, Delegate method, Object args, Int32 numArgs, DelegatecatchHandler)

SerializeCollection 方法:

public static string SerializeCollection<T1>(ObservableCollection<T1> coll)
{
var xs = new XmlSerializer(typeof (ObservableCollection<T1>));
using (var writer = new StringWriter())
{
xs.Serialize(writer, coll);

return writer.ToString();
}
}

最佳答案

尝试在类的顶部添加 Serializable 属性。

[Serializable] // Set this attribute to the class that you want to serialize
public class XMLColumns
{
public string FieldName { get; set; }
public DataTemplate CellTemplate { get; set; }
public DataTemplate GroupValueTemplate { get; set; }
//public object EditSettings { get; set; }
}

然后你可以通过这样做来序列化你的对象:

public void SerializeXMLColumns()
{
XMLColumns col = new XMLColumns();
col.FieldName = "Field1";
col.CellTemplate = new CellTemplate();
col.GroupValueTemplate = new GroupValueTemplate();
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyXMLColumns.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, col);
stream.Close();
}

并以这种方式反序列化:

public void DeserializeXMLColumns()
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("XMLColumns.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
XMLColumns col = (XMLColumns) formatter.Deserialize(stream);
stream.Close();

// Test
Console.WriteLine("FieldName: {0}", col.FieldName);
Console.WriteLine("CellTemplate: {0}", col.CellTemplate.ToString());
Console.WriteLine("GroupValueTemplate: {0}", col.GroupValueTemplate.ToString());
}

还请考虑:

It is important to note that the Serializable attribute cannot be inherited. If you derive a new class from MyObject, the new class must be marked with the attribute as well, or it cannot be serialized.

因此您还需要在 DataTemplate 类的顶部添加 Serializable 属性。

[Serializable]
public class DataTemplate
{
...
}

看看:MSDN - Basic Serialization .

关于c# - DataTemplate 序列化期间出现 InvalidOperationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31156260/

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