I want to only allow my WPF window to be resized horizontally. How best can I achieve this?
Building on the answers from User3810621 and others, this can be turned into a reusable behavior which locks in the calculated sizes as min and/or max after the first content render:
namespace whatever.util.wpf.behaviors
{
using System.Windows;
using System.Windows.Interactivity;
public class LockInitialSize : Behavior
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.ContentRendered += OnContentRendered;
}
protected override void OnDetaching()
{
// possibly detached before ever rendering
AssociatedObject.ContentRendered -= OnContentRendered;
base.OnDetaching();
}
private void OnContentRendered(object s, EventArgs e)
{
// Just once
AssociatedObject.ContentRendered -= OnContentRendered;
if (MinWidth)
{
AssociatedObject.MinWidth = AssociatedObject.ActualWidth;
}
/// ... MaxWidth, MinHeight, MaxHeight
}
#region MinWidth Property
public bool MinWidth
{
get => (bool)GetValue(MinWidthProperty);
set => SetValue(MinWidthProperty, value);
}
public static readonly DependencyProperty MinWidthProperty =
DependencyProperty.Register(nameof(MinWidth), typeof(bool), typeof(LockInitialSize));
#endregion
// ... MaxWidth, MinHeight, MaxHeight
}
}
The remaining, repetitive values are trivial and omitted for brevity.
Usage: