<Grid
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<Button Name="butMain" Click="Clicked">Click Me!</Button>
<x:Code><![CDATA[
</x:Code>
</Grid>
You forgot the closing tag for the CDATA section. I'm guessing from your example you're using a site-of-origin file but I'd highly recommend re-thinking that if this is
your XAML file and not something intrinsically external. You can set the Build Action to "Page" which will compile the XAML into a BAML file embedded in the assembly. Not only does it reduce the number of individual files in your release but also allows easy loading with:
Page page = Application.LoadComponent(new Uri("/Page1.xaml", UriKind.Relative)) as Page;
if (page != null)
gridMain.Children.Add(page);
This will work just fine but you will be warned that a
Page
isn't intended to be the child of anything other than a
Window
or
Frame
. That could be easily remedied by just wrapping the loaded
Page
in a
Frame
and adding that as a child to the
Grid
.
Example:
Uri uri = new Uri("/Page1.xaml", UriKind.Relative);
Page page = Application.LoadComponent(uri) as Page;
Frame frame = new Frame();
frame.Content = page;
gridMain.Children.Add(frame);
My full working code:
<Window x:Class="Testing_xClass_and_xCode.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Testing_xClass_and_xCode"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid Name="gridMain" />
</Window>
<Page x:Class="Testing_xClass_and_xCode.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Testing_xClass_and_xCode"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Title="Page1">
<Grid
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<Button Name="butMain" Click="Clicked">Click Me!</Button>
<x:Code>
<![CDATA[
</x:Code>
</Grid>
</Page>
namespace Testing_xClass_and_xCode
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
try
{
Page page = Application.LoadComponent(new Uri("/Page1.xaml", UriKind.Relative)) as Page;
if (page != null)
gridMain.Children.Add(page);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
}
EDIT: A short note: As John Simmons pointed out, you should consider making this a
UserControl
instead. A
Page
is designed to be navigable. All you're doing is encapsulating controls which is why
UserControl
exists. That being said, WPF is very flexible and will let you do most anything.