Search code examples
wpfwidthmainwindow

Changing the width of Window when using pages in WPF


Im using pages in the WPF project that im currently working on. However i can't seem to figure out how to change the width of a page, or rather, the width of the window that hosts the pages?

Setting the page width property only changes the width of the page inside the window frame.

Setting the with of the mainwindow or navigationwindow through:

<Application.MainWindow>
    <Window Width="400" />
</Application.MainWindow>

<Application.MainWindow>
    <NavigationWindow Width="400" />
</Application.MainWindow>

Doesnt work either. So how do i set the width of the window in XAML?


Solution

  • It is indeed a pain: you need a NavigationWindow that can navigate to the page. As this inherits from Window you can set the Height and Width on this container.
    -Open a new wpf aplication
    -delete the standard window1 you get.

    Change the App.xaml thus (delete the StartupUri attribute):

    <Application x:Class="WpfApplication1.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Startup="Application_Startup">
    <Application.Resources>
    
    </Application.Resources>
    </Application>
    

    Write the App.xaml.cs thus:

        public partial class App : Application
    {
        private NavigationWindow navigationWindow;
    
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            navigationWindow = new NavigationWindow();
            navigationWindow.Height = 200;
            navigationWindow.Width = 100;
            var page = new Page1();
            navigationWindow.Navigate(page);
            navigationWindow.Show();
        }
    

    you can add a page from the project menu. This will give you something like:

    <Page x:Class="WpfApplication1.Page1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Page1">
    <Grid>
        <TextBlock>test</TextBlock>
    </Grid>
    </Page>
    

    Good luck!