WPF Window - Only allow horizontal resize

后端 未结 8 1094
一生所求
一生所求 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:52

    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.

    0 讨论(0)
  • 2021-01-03 23:59

    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;
    }
    
    0 讨论(0)
提交回复
热议问题