Reputation: 2626
In my project I have fixed header & footer, and changeable content. so i have put ContentControl in my window.
<Grid>
<Canvas Name="canvas_Logo" HorizontalAlignment="Center" VerticalAlignment="Top" Width="180">
<Image Source="Images/k1.png" Grid.Row="1" Width="180" />
</Canvas>
<ContentControl VerticalAlignment="Center" Name="CC1" Grid.Row="2" Height="450"/>
<Canvas x:Name="canvas_Marque" ClipToBounds="True" Height="60" HorizontalAlignment="Center" VerticalAlignment="Bottom" Width="1022" Background="DarkRed" />
</Grid>
It look like this...
I have create two user control name page1, page2. Page 1 has a button, when i click the button ContentControl has show page2.
so i have write the below code in button1_Click
MainPage n = new MainPage();
n.CC1.Content = new Page2();
But at the time of button click ContentControl not changed what can i do for that?
My page1 xaml
<Grid Background="AliceBlue">
<Label Content="Child1" Height="28" HorizontalAlignment="Left" Margin="74,65,0,0" Name="label1" VerticalAlignment="Top" Width="157" />
<Button Content="load page2 and destroy this" Height="31" HorizontalAlignment="Left" Margin="79,124,0,0" Name="button1" VerticalAlignment="Top" Width="186" Click="button1_Click" />
</Grid>
page2 xaml
<Grid Background="CadetBlue">
<Label Content="This is page 2" Height="28" HorizontalAlignment="Left" Margin="96,82,0,0" Name="label1" VerticalAlignment="Top" Width="148" />
</Grid>
How to change the content control Content in WPF?
Upvotes: 0
Views: 4669
Reputation: 2315
You cannot instantiate a new MainPage from the Page1 UserControl, since MainPage is already the host of Page1 (if I understand you right). If you're going to manage pages from the code-behing (not the best practice ref. @Noctis), you must do all the work from the MainPage.xaml.cs in this case. You must then find some way to pass arguments back to MainPage in order to change the content. Usually this is done in a ViewModel, as @Noctis says.
Upvotes: 0
Reputation: 11763
Ah, my friend ... we meet again ... Good to see you're making progress on your project...
Now, my next suggestion would be: Don't do these things from the code behind ... Let the XAML binding to it's work ...
Usually, Using MVVM, you'll have your content control source binding on a property of a base view model type. So, let's assume VM1
and VM2
both extend BasicViewModel
, and you have a property defined like this:
Public BasicViewModel Current_VM {get;set;}
Now, all you need to do when you want to swap, is change the Current_VM
from VM1
to VM2
, and the binding will do the rest, updating your window to the correct view (assuming you have the data templates set .. but you never said if you're using MVVM or not ...)
Upvotes: 2