如何在运行时从其XAML字符串添加WPF网格控件?

时间:2010-10-17 14:44:39

标签: wpf xaml wpf-controls runtime

假设我们有一个如下所示的网格XAML - 例如。从方法返回的生成字符串。

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width='*' />
        <ColumnDefinition Width='*' />
    </Grid.ColumnDefinitions>
    <TextBlock Text='id' Grid.Column='0'/>
    <Rectangle Fill='Black' Grid.Column='1' />
</Grid>

我想要做的是创建这样一个网格并在运行时添加到堆栈面板,代码如下所示。

XmlReader xr = XmlReader.Create(input: new StringReader(g.xaml));
var control = XamlReader.Load(xr) as Grid;
this.stackPanel.Children.Add(control);

我使用的表格是:

<Window x:Class='AllRibbonBrushes.MainWindow'
        xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'
        xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
        Title='MainWindow' Height='223' Width='533' 
        Loaded='Window_Loaded'>
    <ScrollViewer>
       <StackPanel Name="stackPanel">
          <!--The runtime grid need to be added here-->
       </StackPanel>
    </ScrollViewer>
</Window>

但我收到错误Cannot create unknow type 'Grid'。我通过添加按钮/文本块成功完成此操作但未能添加具有嵌套控件的网格。

如果您知道如何操作,请分享。欢迎所有的帮助,非常感谢!

1 个答案:

答案 0 :(得分:4)

xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'添加到您要加载的xaml中的第一个Grid元素。这会将wpf命名空间声明为xaml中的默认命名空间。然后XamlReader.Load可以找出什么样的控件。

<Grid xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width='*' />
        <ColumnDefinition Width='*' />
    </Grid.ColumnDefinitions>
    <TextBlock Text='id' Grid.Column='0'/>
    <Rectangle Fill='Black' Grid.Column='1' />
</Grid>
相关问题