Pergunta

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

Foi útil?

Solução 2

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!

Outras dicas

You have to define a parameterless constructor in your TextBox_Element.

XamlReader.Load by default will always look for an empty constructor while if it has a required parameters you'll have to add more work.

According to Max Galkin

It's a "feature" of the XAML language, it is declarative and doesn't know anything about constructors. People use ObjectDataProvider in XAML to "translate" and wrap instances of classes that do not have a parameterless constructor (it's [also useful for data binding][2]).

In your case it'll be approximately like this:

<ObjectDataProvider ObjectType="TextBox_Element">
    <ObjectDataProvider.ConstructorParameters>
        <x:Double>400</x:Double>
        <x:Double>200</x:Double>
    </ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>


var textBoxElem = (TextBox_Element) ((ObjectDataProvider)XamlReader.Parse(xamlStr)).Data;

Assuming your TextBox_Element constructor looks like this

public class TextBox_Element
{
  public TextBox_Element(double left, double top)
  {
    // do whatever
  }
}

Perhaps the file it saved to did not contain the information required on your custom element? Just as if you save a textbox, the XamlReader needs to have the xmlns references to be able to read it.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top