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

时间:2014-06-27 12:55:56

标签: c# wpf

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

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

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

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

但是什么样的组合能达到我的目的呢?

2 个答案:

答案 0 :(得分: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>

编辑:如果您想在代码隐藏中执行此操作,就像您在评论中所写的那样,您可以按照以下方式执行此操作:

<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>

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

public MainWindow()
{
    InitializeComponent();

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

}

请注意:上面的childElement将是您的UserControl。

答案 1 :(得分:0)

使用WindowChrome.ResizeBorderThickness属性,可以更简单的方式实现,而无需使用MinWidth,MaxWidth和ActualHeight属性。 例如,请考虑以下可用于窗口的样式,以仅允许调整高度:

    <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                     xmlns:System="clr-namespace:System;assembly=mscorlib"
    x:Class="YourResourceDictionaryClass" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:shell="http://schemas.microsoft.com/winfx/2006/xaml/presentation/shell">

<Style x:Key="AllowResizeHeightOnlyWindow" TargetType="{x:Type Window}">
<Setter Property="shell:WindowChrome.WindowChrome">
            <Setter.Value>
                <shell:WindowChrome ResizeBorderThickness="0, 2"
                            />
            </Setter.Value>
        </Setter>
</Style>

希望这有帮助