Search code examples
c#wpfxamlxamlreader

Wpf xamlreader load xaml with custom elements


I got a canvas with custom elements, similar to texboxes and shapes.

<Canvas Name="SomeCanvas" >
    <TextBox_Element   Canvas.Left="400" Canvas.Top="200" Height="50" Name="s3" Background="#57FF3ACB"  />
</Canvas>

Which im saving to a file with:

SerializeToXML(filename, SomeCanvas);

Later I´m trying to load that file and convert ist back to the original canvas with:

FileStream fs = File.Open(openFileDialog.FileName, FileMode.Open, FileAccess.Read);
Canvas savedCanvas = XamlReader.Load(fs) as Canvas;

The last method throws a XamlParseException:

No matching constructor found on type '...TextBox_Element'. You can use the Arguments or FactoryMethod directives to construct this type.'

Does anybody know how to restore the canvas the way it was from the file? Thanks


Solution

  • Do you have a parameterless constructor in your custom class? If not, try this:

    public class TextBox_Element{
    
        public TextBox_Element(double x, double y){
            // code
        }
        public TextBox_Element(){
            // emptyness
        }
    }
    

    That worked for me, i hope itsolves your problem too!