Wpf 使用XamlReader从字符串创建网格

Wpf 使用XamlReader从字符串创建网格,wpf,grid,xamlreader,Wpf,Grid,Xamlreader,我有一个XAML网格的字符串表示,如下所示: <Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <Canvas Background="Yellow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"> <Label Content="textik" />

我有一个XAML网格的字符串表示,如下所示:

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

我需要做的是用这个字符串创建一个网格对象。我尝试了很多方法,但到目前为止,最接近的方法是下面的代码:

string content = "<Grid xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><Canvas Background=\"Yellow\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><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;
字符串内容=”;
//字符串是通过编程方式创建的,我只是把它放在这里,看看它在过程结束时是什么样子
Stream=newmemoryStream(System.Text.ascienceoding.ASCII.GetBytes(content));
objectobjgrid=XamlReader.Load(流);
Grid myGrid=(Grid)objGrid;
但是,发生XamlParsedException时表示缺少根元素

我在XAML代码中是否有我看不到的错误?还是这种方法不好


感谢您的回答

尝试添加
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml“
到根网格元素。此外,您不需要在画布中再次使用xmlns(但这也不会造成任何伤害,只是字符串变得不必要的大)。

您使用的是什么版本的框架?在4中,System.Xaml中有更多更灵活的类。您可以使用
System.Xaml.XamlServices.Load(流)
以获取松散xaml中的精确网格对象。但是,在VS2010中同时使用4和3.5,您的确切代码(在第二个代码段中)将返回预期结果。不确定问题出在您这边,但可能不是您发布的代码。

结果表明,问题确实不在我发布的代码上。根据前面的解决方案,我正在读取流以查看其中的内容,而ReadToEnd()方法将流的开头移到了结尾,因此XamlReader.Read()没有获得完整的内容…string content=“第二个xmlns(在画布中)是通过XamlReader.Read()创建的.你看,我现在做的是加载一个xaml文件,用代码玩一些游戏,然后尝试从结果字符串创建一个网格。这只是一个副作用。。