InvalidOperationException while serializing DataTemplate
I am trying to find a way to Serialize 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);
}
}
The Serialize function throws an exception that I cannot serialize a DataTemplate
.
Here is the data structure:
public class XMLColumns
{
public string FieldName { get; set; }
public DataTemplate CellTemplate { get; set; }
public DataTemplate GroupValueTemplate { get; set; }
//public object EditSettings { get; set; }
}
thank
EDIT:
Exception: InvalidOperationException
StackTrace:
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 method:
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();
}
}
source to share
Try adding an attribute Serializable
to the top of your class.
[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; }
}
Then you can serialize your object by doing the following:
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();
}
And deserialize this path:
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());
}
Please also consider:
It is important to note that the Serializable attribute cannot be inherited. If you have derived a new class from MyObject, the new class must also be tagged or cannot be serialized.
So, you need to add an attribute Serializable
at the top of the class as well DataTemplate
.
[Serializable]
public class DataTemplate
{
...
}
Take a look at: MSDN - Basic Serialization .
source to share