1

我有一个 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>

我需要做的是用这个字符串创建一个 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;

但是,发生 XamlParsedException 表示缺少根元素。

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

感谢您的回答

4

2 回答 2

2

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

于 2010-09-25T21:05:11.547 回答
0

也尝试添加xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"到根 Grid 元素。此外,您不需要在 Canvas 中再次使用 xmlns(但它也不会受到伤害 - 除了您的字符串变得不必要的大)。

于 2010-09-24T11:17:27.020 回答