如何只允许WPF窗口的高度调整大小?

tet*_*ete 1 c# wpf

具体而言,我有一个Window,其Content被设置为UserControl.并且我想允许用户拖动以增加高度Window,但Width应该是固定的且不可调整大小.我想我有这样的属性可以修改,但我不能让它们按我的意愿行事:

  • Window.SizeToContent,可用值:手动,宽度,高度,

  • WidthAndHeight Window.ResizeMode,可用值:CanMinimize,
    CanResize,CanResizeWithGrip,NoResize

  • 当然还有最小/最大高度,宽度 UserControl

但是什么样的组合可以实现我想要的呢?

小智 6

一种方法是将两个窗口MinWidthMaxWidth窗口设置为相同的值:

<Window x:Class="WpfApplication20.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" MinWidth="525" MaxWidth="525">
    <Grid>

    </Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)

编辑:如果你想在代码隐藏中这样做,就像你在评论中写的那样,你可以这样做:

<Window x:Class="WpfApplication20.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350">
    <Rectangle x:Name="childElement"  Width="525" Fill="Red">

    </Rectangle>
</Window>
Run Code Online (Sandbox Code Playgroud)

在窗口的构造函数中,您会写:

public MainWindow()
{
    InitializeComponent();

    Binding binding = new Binding("ActualWidth") { Source = childElement };
    BindingOperations.SetBinding(this, MinWidthProperty, binding);
    BindingOperations.SetBinding(this, MaxWidthProperty, binding);

}
Run Code Online (Sandbox Code Playgroud)

请注意:childElement以上是您的UserControl.