In WPF I have a window for which I want the height to be sized to content (and adjusted dynamically as I have an Expander in it) and prevent the user from being able to change it but let him/her being able to change the width of the window.
How can I achieve this?
SizeToContent does half the trick as it doesn’t restrict manual changing the height. ResizeMode cannot prevent changing just the height or the width. And in the SizeChanged event I cannot distinguish if the change is initiated automatically or by the user to prevent changing the height.
You can use the FrameworkElement.MinHeight
and FrameworkElement.MaxHeight
properties to freeze the current height of the Window
MainWindow.xaml.cs
partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// Lock the initial height from the Loaded event handler
this.Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
=> LockWindowHeight();
private void LockWindowHeight()
=> this.MinHeight = this.MaxHeight = this.ActualHeight;
private void SetWindowHeight(double newHeight)
{
this.MinHeight = double.IsNormal(newHeight) ? newHeight : 0;
this.MaxHeight = double.IsNormal(newHeight) ? newHeight : double.PositiveInfinity;
this.Height = newHeight;
}
// For the sake of completeness
private void UnlockWindowHeight(double newHeight)
{
this.MinHeight = 0;
this.MaxHeight = double.PositiveInfinity;
}
}