Suppose I have the following class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NetworkSwitcher
{
[Serializable]
class testClass
{
public string str;
public testClass(string _str)
{
this.str = _str;
}
}
}
Now when I try to execute the following, it throws a System.Windows.Markup.XamlParseException.
testClass tc = new testClass("Hello World");
XmlSerializer xsl = new XmlSerializer(typeof(testClass));
TextWriter WriteFileStream = new StreamWriter(@"C:\NSProfiles.xml");
xsl.Serialize(WriteFileStream, tc);
WriteFileStream.Close();
If I use a simple String type object instead of tectClass, the code works fine:
string data = "hello world";
XmlSerializer xsl = new XmlSerializer(typeof(String));
TextWriter WriteFileStream = new StreamWriter(@"C:\NSProfiles.xml");
xsl.Serialize(WriteFileStream, data);
WriteFileStream.Close();
So I guess the problem is in the class definition, how can I fix it? I am using WPF, not WinForms and I don’t have any prior experience in WPF or XMLSerialization. Let me know if I shall provide any other useful information.
To fix the error, add a default constructor to the class (a constructor that takes no arguments).
Doing this alone will stop the error from happening, but may not serialize the string value correctly. I’m not 100% sure on that, as it may be able to serialize a public member variable.
If not, you’ll want to add a public Property for the string value.
A more “standard” implementation of this class would likely look like the following. You would either have a second constructor or just use the setter to set the value:
Edit: Added the public modifier to the class. Should work now.
Also, I am guessing you are calling the code that throws the exception in the constructor of the Window? That is the only reason I can see that this would throw a XAML exception. Errors in the constructor get wrapped in that XAML exception, so in these cases you want to look at the InnerException to find the problem.