WPF Window - Only allow horizontal resize

后端 未结 8 1095
一生所求
一生所求 2021-01-03 23:02

I want to only allow my WPF window to be resized horizontally. How best can I achieve this?

8条回答
  •  离开以前
    2021-01-03 23:41

    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:

    
        
            
        
    

提交回复
热议问题