Search code examples
c#xamlwindows-phone-8uwpuwp-xaml

Embed XAML file's contents in another XAML file


I figured that this is pretty basic, but I need to take elements from elements.xaml and put it in Template.xaml as a child of the main grid "MainGrid". This can be done with either c# or XAML, it doesn't really matter.

Here is elements.xaml:

<TextBox Text='' FontSize='25' Grid.Column='0' Grid.Row='1'/>
<TextBox Text='' FontSize='25' Grid.Column='1' Grid.Row='1'/>
<TextBox Text='' FontSize='25' Grid.Column='2' Grid.Row='1'/>
<TextBox Text='' FontSize='25' Grid.Column='3' Grid.Row='1'/>

Here is Template.xaml:

<Grid x:Name="MainGrid" Margin="20" Background="{ThemeResource SystemControlAltMediumLowAcrylicElementMediumBrush}">
    <Grid.RowDefinitions>
        //Defs go here
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        //Defs go here
    </Grid.ColumnDefinitions>
    <TextBlock x:Name="Head00" TextWrapping="Wrap" Text="Scene" FontSize="50" Grid.Column="0" Grid.Row="0"/>
    <TextBlock x:Name="Head10" Text="Characters" FontSize="50" Grid.Column="1" Grid.Row="0"/>
    <TextBlock x:Name="Head20" Text="Page" FontSize="50" Grid.Column="2" Grid.Row="0"/>
    <TextBlock x:Name="Head30" Text="Mic Assignment Number" FontSize="50" Grid.Column="3" Grid.Row="0"/>
</Grid>

I want the embedded XAML to go under the Textblocks. Can you guys help?

EDIT: elements.xaml is in the applicationdata folder, at C:\Users\USERNAME\AppData\Local\Packages\PACKAGENAME\LocalState

Thanks, Rajan


Solution

  • Try using XamlReader, it can load XAML string content, and convert the string to the corresponding XAML element.

    Here is a simple example:

            string defaultNamespace = "http://schemas.microsoft.com/winfx/2006/xaml/presentation";
            string xaml = "<TextBlock xmlns=\"" + defaultNamespace + "\">Hello, world!</TextBlock>";
            // xaml content will be:
            // <TextBlock xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation">Hello, world!</TextBlock>
            var textBlock = XamlReader.Load(xaml) as TextBlock;
            this.rootGrid.Children.Add(textBlock);
    

    This example will bring a TextBlock to UI.

    For more info about XamlReader, you can visit XamlReader Class.