Domanda

Ho alcune rappresentazioni di stringa di oggetti XAML, e voglio costruire i controlli. Sto utilizzando la funzione di XamlReader.Parse per fare questo. Per un semplice controllo, ad esempio Button che ha un costruttore di default non prendere alcun parametro questo funziona bene:

var buttonStr = "<Button xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">Text</Button>";
var button = (Button)XamlReader.Parse(buttonStr); 

Tuttavia, quando provo a fare questo per esempio un controllo Stroke fallisce. In primo luogo provare una semplice corsa a vuoto:

var strokeStr = "<Stroke xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"></Stroke>";
var stroke = (Stroke)XamlReader.Parse(strokeStr);

Questo dà l'errore:

  

Non è possibile creare l'oggetto di tipo 'System.Windows.Ink.Stroke'. CreateInstance fallito, che può essere causata da non avere un costruttore predefinito pubblico per 'System.Windows.Ink.Stroke'.

Nella definizione di Stroke vedo che ha bisogno di almeno uno StylusPointsCollection da costruire. Presumo che questo è ciò che l'errore mi sta dicendo, anche se era un po 'assumendo questo sarebbe gestita dal XamlReader. Cercando di trasformare un Xaml di corsa con StylusPoints in esso dà lo stesso errore:

var strokeStr = 
    "<Stroke xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">" + 
        "<Stroke.StylusPoints>" + 
            "<StylusPoint X=\"100\" Y=\"100\" />" +
            "<StylusPoint X=\"200\" Y=\"200\" />" + 
        "</Stroke.StylusPoints>" + 
    "</Stroke>";
var stroke = (Stroke) XamlReader.Parse(strokeStr);

Che cosa sto facendo di sbagliato? Come faccio a dire il XamlReader come creare Stroke correttamente?

È stato utile?

Soluzione

E 'una "caratteristica" del linguaggio XAML, è dichiarativa e non sa nulla di costruttori.

La gente usa ObjectDataProvider in XAML a "tradurre" e avvolgere istanze di classi che non hanno un costruttore senza parametri (è utile anche per associazione dati ).

Nel tuo caso il codice XAML dovrebbe essere circa così:

<ObjectDataProvider ObjectType="Stroke">
    <ObjectDataProvider.ConstructorParameters>
        <StylusPointsCollection>
            <StylusPoint X="100" Y="100"/>
            <StylusPoint X="200" Y="200"/>
        </StylusPointsCollection>
    </ObjectDataProvider.ConstructorParameters>
</ObjectDataProvider>

E il codice dovrebbe essere:

var stroke = (Stroke) ((ObjectDataProvider)XamlReader.Parse(xamlStr)).Data;

HTH.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top