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.
4 Answers
11
votes
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?
5
votes
5
votes
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.
Window.SizeToContent
set to something other thanManual
? If so,Width
and/orHeight
will effectively be decoupled fromActualWidth
andAcutalHeight
. – dlf