如何防止 WPF 中自动调整大小的 TextBox 增长 window

How to prevent growing of TextBox in WPF auto-sized window

我有这个显示标签、按钮和文本框的 WPF 应用程序,如下所示:

通过按钮再添加三行后,windwos 开始随文本框一起增长:

这是XAML:

<Window x:Class="_99_TestWPFApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Title="Simple WPF Test App" Height="Auto" Width="Auto" SizeToContent="WidthAndHeight">
<Grid x:Name="MainGrid">
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Label Grid.Row="0" Grid.Column="0" Content="A LABEL" "/>
    <Button Grid.Row="1" Grid.Column="0" x:Name="btnAdd" Click="btnAdd_Click" Content="ADD LINE" />
    <TextBox  Grid.Row="0" Grid.Column="1"  Grid.RowSpan="2"  VerticalScrollBarVisibility="Visible" Width="150"/>
</Grid>

为了将文本框的高度绑定到网格的高度,我也将此添加到文本框Height="{Binding ElementName=MainGrid, Path=ActualHeight}"但没有效果。

我希望固定 window 和网格大小,同时文本框通过滚动条显示其内容

这可能吗?或者我是否必须在某处设置固定高度(例如 window)?

其实是可以的:经过一些实验,我找到了一个可能的解决方案:

<Window x:Class="_99_TestWPFApp.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Title="Simple WPF Test App" Height="Auto" Width="Auto" SizeToContent="WidthAndHeight">
<Grid x:Name="OuterGrid">
    <Grid.RowDefinitions>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <Grid x:Name="LeftInnerGrid">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Label Grid.Row="0" Grid.Column="0" Content="A LABEL"/>
        <Button Grid.Row="1" Grid.Column="0" x:Name="btnAdd" />
    </Grid>
    <!-- notice the additional grid and the binding of the height here -->
    <Grid Name="RightInnerGrid" Grid.Row="0" Grid.Column="1" Height="{Binding ElementName=OuterGrid, Path=ActualHeight}">
        <TextBox   VerticalScrollBarVisibility="Visible" Width="150"/>
    </Grid>
</Grid>

将文本框添加到它自己的网格中并将内部网格的高度 属性 绑定到外部网格的高度就达到了目的。