views:

36

answers:

1

Let's say we have a grid XAML like below - eg. a generated string returned from a method.

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

What I want to do is to create such a grid and added to a stackpanel at run time, codes similar as below.

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

The form I use is:

<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>

But I get the error Cannot create unknow type 'Grid'. I succeed doing this by adding a button/a textblock but failed to add a grid with nested controls.

If you know how to do so, please share. All helps are welcome and very much appreciated!

+1  A: 

Add xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' to the first Grid element in the xaml you would like load. This declares the wpf namespace the default namespace in your xaml. XamlReader.Load can then find out what kind of control is.

<Grid xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation'&gt;
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width='*' />
        <ColumnDefinition Width='*' />
    </Grid.ColumnDefinitions>
    <TextBlock Text='id' Grid.Column='0'/>
    <Rectangle Fill='Black' Grid.Column='1' />
</Grid>
Lars Truijens