I want to only allow my WPF window to be resized horizontally. How best can I achieve this?
If you have the following requirements: * Width can be user resized (ResizeMode=CanResize) * Height is automatically sized (SizeToContent=Height)
It won't work for two reasons: * there is no ResizeMode=CanResizeHeight * when the user resizes the window, it will clobber SizeToContent to "Manual"
A simple hack I use is to constantly force "SizeToContent" back to my desired value.
<Window x:Class="MyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
SizeToContent="Height"
ResizeMode="CanResize"
LayoutUpdated="LayoutUpdated">
private void LayoutUpdated(object sender, EventArgs e)
{
SizeToContent = SizeToContent.Height;
}
You can also use the ContentRendered event. The PropertyChanged event won't work. This isn't perfect, since the user can still move the cursor vertically, and it will cause some flickering if done quickly.
If you want to use the MinHeight
and MaxHeight
approach but still allow the window to automatically size itself to fit the size of its content:
<Window x:Class="MyWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
SizeToContent="WidthAndHeight"
ResizeMode="CanResize"
Loaded="window_Loaded">
In code-behind:
private void window_Loaded(object sender, RoutedEventArgs e)
{
this.MinWidth = this.ActualWidth;
this.MinHeight = this.ActualHeight;
this.MaxHeight = this.ActualHeight;
}