DataTemplate序列化期间的InvalidOperationException

时间:2015-07-01 08:29:21

标签: c# wpf serialization datatemplate

我正在尝试找到一种序列化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();
                }
            }

1 个答案:

答案 0 :(得分:0)

尝试在课程顶部添加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());
}

还请考虑:

  

请务必注意,不能继承Serializable属性。如果从MyObject派生新类,则新类也必须使用该属性标记,否则无法序列化。

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

[Serializable]
public class DataTemplate
{
    ...
}

看看:MSDN - Basic Serialization