【问题标题】:How to add a WPF grid control from its XAML string at runtime?如何在运行时从其 XAML 字符串添加 WPF 网格控件?
【发布时间】:2010-10-19 01:06:08
【问题描述】:

假设我们有一个如下所示的网格 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'。我通过添加按钮/文本块成功地做到了这一点,但未能添加带有嵌套控件的网格。

如果你知道怎么做,请分享。欢迎所有帮助,非常感谢!

【问题讨论】:

    标签: wpf xaml wpf-controls runtime


    【解决方案1】:

    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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多