views:

30

answers:

2

I have a string representation of a XAML Grid like this:

<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&gt;
    <Canvas Background="Yellow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"&gt;
        <Label Content="textik" />
    </Canvas>
</Grid>

What I need to do is create a Grid object out of this string. I tried a lot of approaches, but so far the closest is the code below:

string content = "<Grid xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"&gt;&lt;Canvas Background=\"Yellow\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"&gt;&lt;Label Content=\"textik\" /></Canvas></Grid>";

// the string is created programatically, I just put it here to see what it looks like at the end of the process

Stream stream = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(content));

object objGrid = XamlReader.Load(stream);
Grid myGrid = (Grid) objGrid;

However, the XamlParsedException occurs saying that the root element is missing.

Do I have a mistake in a XAML code that I just cannot see? Or is the approach bad?

Thanks for an answer

A: 

Try also adding xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" to the root Grid element. Also you do not need the xmlns again in Canvas (but it doesn't hurt either - except that your strings become unnecessarily big).

bitbonk
The second xmlns (in canvas) is created through the XamlReader.Read(). You see, what I am doing is I load a xaml file, play some games with the code and then try to create a grid from resulting string. This is just a side effect..
Gal
+1  A: 

What version of the framework are you using? In 4 you have additional classes in System.Xaml that are more flexible. You can use System.Xaml.XamlServices.Load(stream); to get the exact Grid object in the loose xaml. However, using both 4 and 3.5 in VS2010, your exact code (in the second snippet) returns the expected result. Not sure what the problem is on your side but it might not be the code you posted.

Alex Paven
Turned out that the problem was really not at the code I posted. From earlier sollutions, I was reading the stream to see what is inside and the method ReadToEnd() moved the beginning of the stream to the end, so the XamlReader.Read() did not get full content...
Gal
string content = "<Grid....";Stream stream = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(content));StreamReader reader = new StreamReader(stream);string whatsInside = reader.ReadToEnd();object objGrid = XamlReader.Load(stream);Grid myGrid = (Grid) objGrid;
Gal