Alexander
Alexander

Reputation: 3

WPF set window height sized to content and width adjustable manually

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.

Upvotes: 0

Views: 51

Answers (2)

Alexander
Alexander

Reputation: 3

For the full solution several event handlers and a simple method need to be added:

...
expander.Expanded += Expander_StateChanged;
expander.Collapsed += Expander_StateChanged;
this.SizeChanged += Window_SizeChanged;
...

private void Expander_StateChanged(object sender, RoutedEventArgs e)
    => AdjustWindowHeight();

private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
  => LockWindowHeight();

void AdjustWindowHeight()
{
    UnlockWindowHeight();
    this.SizeToContent = SizeToContent.Height;
}

Upvotes: 0

BionicCode
BionicCode

Reputation: 29028

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

Upvotes: 0

Related Questions