Resize wpf window programmatically in C #

I have a wpf window with two user controls, inside which the second is displayed only if necessary. I just set the MinWidth of the window in XAML, MinHeight is provided through data binding to the ist set, depending on whether the second user control is displayed. Now: how can I set the window size for different values ​​than MinWidth / Height at run time. I tried setting the values ​​before Show () after Show () in various events (Initialized, Loaded, etc.). I tried with UpdateLayout () and without it, I tried to set the height / width ratio to the data binding. Nothing works! But when I debug the approaches, I see that the Height / Width properties in the window are set to the expected values, but ActualHeight / Width remains. I thought it would be a bagatelle, but it turned out that it was not (for me). Yours for any help.

+6
source share
3 answers

Did you try to install

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 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> 

Press the button to set the height of the window. Is this what you are looking for?

+8
source

You don’t have much information, so I’m just guessing here.

The only way I could play a window without respecting its width and height settings was when I set SizeToContent to WidthAndHeight .

+1
source

If someone is still struggling with this, you only need 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, simply write the following code in the .cs file of the new window.

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

Hope this helps.

+1
source

Source: https://habr.com/ru/post/895300/


All Articles