Click here to Skip to main content
15,887,477 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello,

I tried the usual approach of initializing a window to a Page, but it does not work,

the code im using:

window.xaml.css:
private void show_page_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("This should open the -page- window");
            var mypage = new Page();
            mypage.Show();
       }


Is it even possible to start an instance of a page from inside a window method?

waiting for replies
thanks
Posted

1 solution

Ok, the thing is that the Page control can only be shown in a Frame or a NavigationWindow when using a WPF application, so what you need to do is:


In the Window XAML you need to add a Frame control as shown bellow:


XML
<Window x:Class="WpfTestPageQuestion.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Button Content="Load Page" Click="show_page_Click"/>
        <Frame Grid.Row="1" x:Name="frame"/>
    </Grid>
</Window>

Then you need to add the handler for the Click Event for the button click:


C#
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void show_page_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("This should open the -page- window");

        // Start the Page control
        var mypage = new Page();
        // Set a Background to make a little more visible the change
        mypage.Background = Brushes.Red;
        // Add any content to your Page
        mypage.Content = new TextBlock
        {
            Text = "Hello from the Page!",
            FontSize = 30,
            VerticalAlignment = System.Windows.VerticalAlignment.Center,
            HorizontalAlignment = System.Windows.HorizontalAlignment.Center
        };

        // Add the Page instance to the Frame contained in the Window XAML
        frame.Content = mypage;

        // Happy message saying that we have successfully addend the Page
        MessageBox.Show("Page shown =D");
    }
}

And you are done. A Page content addent to the Window.


Hope this helps.


All Best

Raul Mainardi Neto

 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900