Resizing wpf window programmatically in c#

31,438

Solution 1

Have you tried to set

Application.Current.MainWindow.Height = 100;

Short addition: I just did a short test, in code:

public partial class MainWindow : Window, INotifyPropertyChanged
{
    private int _height;
    public int CustomHeight
    {
        get { return _height; }
        set
        {
            if (value != _height)
            {
                _height = value;
                if (PropertyChanged != null)
                    PropertyChanged(this, new PropertyChangedEventArgs("CustomHeight"));
            }
        }
    }

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
        CustomHeight = 500;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        CustomHeight = 100;
    }
}

and the XAML:

<Window x:Class="WindowSizeTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="{Binding CustomHeight, Mode=TwoWay}" Width="525">
    <Grid>
        <Button Click="Button_Click">Test</Button>       
    </Grid>
</Window>

Click on the Button sets the window height. Is that what you´re looking for?

Solution 2

You have no given much information, so I am just guessing here.

The only way I could reproduce the window not respecting its width and height settings was when I set SizeToContent to WidthAndHeight.

Solution 3

if someone is still struggling with this, the only thing you have to do is the following:

If you want to resize the main window just write the following code.

Application.Current.MainWindow.Height = 420;

If you want to resize a new window other than the main window just write the following code in the .cs file of the new window.

Application.Current.MainWindow = this; 
Application.Current.MainWindow.Width = 420;

Hope it helps.

Share:
31,438
Admin
Author by

Admin

Updated on July 09, 2022

Comments

  • Admin
    Admin almost 2 years

    I have a wpf window with two usercontrols inside of which the second is only shown when needed. I only set the MinWidth of the window in XAML, the MinHeight is provided through databinding an ist set depending on if the second usercontrol is shown. Now: How can I set the size of the window to different values than the MinWidth/Height during runtime. I tried setting the values before the Show(), after the Show(), in various events (Initialized, Loaded, etc.). I tried with and without UpdateLayout(), I tried setting the Height/Width through databinding. Nothing works! But when I debug the approaches I see that the Height/Width properties of the window are set to the expected values, but ActualHeight/Width stay. I thought it would be a bagatelle but it turned out it is not (to me). Thy for any help.