Tudvari
Tudvari

Reputation: 2905

Loading Grid Definitions at runtime

The XAML code snippet is generated from data of a file.

<Grid.RowDefinitions>
   <RowDefinition Height='0*'/>
   <RowDefinition Height='1*'/>
   <RowDefinition Height='0*'/>
</Grid.RowDefinitions>

My goal is to load this snippet into:

<Window ...>
   <Grid x:Name="TheGrid">
       <!-- HERE -->
   </Grid>
</Window>

So after compiling I can define the grid layout for my software before every launch.

I tried doing this:

using (Stream stream = GenerateStreamFromString(text))
{
   var element = XamlReader.Load(stream) as UIElement;
   grid.Children.Add(element);
}

The problem is that XamlReader.Load(...) throws an exception:

The property element 'Grid.RowDefinitions' is not contained by an object element.

Line number '1' and line position '2'.

The problem (in my opinion) is that in the loading environment there is no Grid element, so there is an invalid reference.

How can I solve this or how can I achieve the same goal easily?

Upvotes: 0

Views: 169

Answers (2)

mm8
mm8

Reputation: 169200

Your XAML code snippet is invalid because it has no root element. Besides, a RowDefinition is not a UIElement that you add to the Children collection of a Grid.

Given the following input data:

string data = "<Grid.RowDefinitions><RowDefinition Height='0*' /><RowDefinition Height='1*' /><RowDefinition Height='0*' /></Grid.RowDefinitions>";

...you could use an XDocument and a GridLengthConverter to create the RowDefinitions:

GridLengthConverter converter = new GridLengthConverter();
foreach (var row in doc.Root.Elements("RowDefinition"))
{
    string height = row.Attribute("Height").Value;
    TheGrid.RowDefinitions.Add(new RowDefinition() { Height = (GridLength)converter.ConvertFrom(height) });
}

Upvotes: 1

Ross
Ross

Reputation: 4568

There is no need to use XAMLReader in this case - just add them directly using code, referencing your Grid by name:

TheGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(0d, GridUnitType.Star)});
TheGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1d, GridUnitType.Star)});
TheGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(0d, GridUnitType.Star)});

Upvotes: 1

Related Questions