I have a simple program. it has a basic canvas with a button and a FRAME.
<Canvas Width="1200" Height="600" Name="frontPanel" Background="Blue">
<Button Width="200" Height="90" Content="flipme" Click="flipme" VerticalAlignment="Top" HorizontalAlignment="Left" >
<Button.RenderTransform>
<TransformGroup>
<TranslateTransform x:Name="BtnMove" X="500" Y="255" />
</TransformGroup>
</Button.RenderTransform>
</Button>
<Frame Name="wow" Width="1200" Height="600"></Frame>
</Canvas>
What I want to accomplish is this, load another xaml page into the current page WITH its back end coding. All I’ve seen online is how to load another page and add the event handlers after its loaded.
my code that loads the page is as follows:
string basePath = AppDomain.CurrentDomain.BaseDirectory;
string commonPath = basePath.Remove(basePath.Length - @"\bin\Debug\".Length);
wow.Source = (new Uri(commonPath + "\\Page2.xaml"));
Alright it works if there are no click methods attached to page2.xaml but when I attach a click event handler to a button in page2.xaml, the program tells me:
Failed to create a 'Click' from the text 'button1_Click_1'.' Line number '12' and line position '144'.
So my questions is there any way for me to load the page and the back end coding together without having to assign it later? cause I made the page2.xaml as a separate page with a separate back end coding. I need to load the page2.xaml in page1.xaml with its back end coding (click event handlers). I reiterate that I have searched the web and still have not find any solution to this problem.
XAML is just a way of constructing objects using a declarative style. It does not contain any “code”, it just constructs objects.
The code in a page is placed in a codebehind file which is a standard .cs file. Note the “partial” keyword in the codebehind. This means it’s just part of a class, with the other part being constructed from the xaml. Both of these parts get compiled into your final class which knows nothing about the xaml used to create it.
If you load a XAML file, that’s all you’re loading. A object that’s constructed from markup.
If you want to encapsulate code behaviour, then you need to load an object, not a xaml file. The most suitable object that comes to mind is the
UserControl, which is created from a xaml file and codebehind like you want.So if you want display objects with their own behaviour, make them UserControls.
If you simply want different displays with the same behaviour, then load them as xaml files and hook up your events manually.