I want to only allow my WPF window to be resized horizontally. How best can I achieve this?
The following solution allows you to leave SizeToContent intact,
doesn't require Win32 Interop or code behind in your Window:
It does rely on Reactive Extensions
In the Package Manager run:
Install-Package System.Reactive
Then you start by creating a new Behavior:
public class VerticalResizeWindowBehavior : Behavior
{
public static readonly DependencyProperty MinHeightProperty = DependencyProperty.Register("MinHeight", typeof(double), typeof(VerticalResizeWindowBehavior), new PropertyMetadata(600.0));
public double MinHeight
{
get { return (double)GetValue(MinHeightProperty); }
set { SetValue(MinHeightProperty, value); }
}
protected override void OnAttached()
{
base.OnAttached();
var window = Window.GetWindow(AssociatedObject);
var mouseDown = Observable.FromEventPattern(AssociatedObject, "MouseLeftButtonDown")
.Select(e => e.EventArgs.GetPosition(AssociatedObject));
var mouseUp = Observable.FromEventPattern(AssociatedObject, "MouseLeftButtonUp")
.Select(e => e.EventArgs.GetPosition(AssociatedObject));
var mouseMove = Observable.FromEventPattern(AssociatedObject, "MouseMove")
.Select(e => e.EventArgs.GetPosition(AssociatedObject));
var q = from start in mouseDown
from position in mouseMove.TakeUntil(mouseUp)
select new { X = position.X - start.X, Y = position.Y - start.Y };
mouseDown.Subscribe(v => AssociatedObject.CaptureMouse());
mouseUp.Subscribe(v => AssociatedObject.ReleaseMouseCapture());
q.ObserveOnDispatcher().Subscribe(v =>
{
var newHeight = window.Height + v.Y;
window.Height = newHeight < MinHeight ? MinHeight : newHeight;
});
}
}
Then you add a UIElement at the bottom of your Window and apply the Behavior:
Set the following Properties on your Window:
ResizeMode="NoResize"
SizeToContent="Width"
Note: In this example, the user is allowed to resize Vertically but not Horizontally
You can easily change the code to allow the opposite, or add properties
to make it configurable.