阻止 ListBox 根据内容调整大小但不根据 window

Stop ListBox from resizing with content but not with window

我的代码中有一个 ListBox,它在创建时将 window 的大小调整为内容的高度,并且不显示它的滚动条,我希望 window从指定尺寸 301*287 开始。如果我将 window 的大小调整得更小,那么 ListBox 的内容会超过它的高度并出现滚动条,这正是我想要的,但我不想必须调整 window 的大小每次创建它都是为了实现这一目标。我尝试了 this question 中的答案,但其中 none 似乎有效。

简而言之,ListBox 应该在创建时根据 301*287 window 上的网格定义调整大小,但实际上并没有,而是根据内容的高度调整自身大小,并使 window的高度比应有的高。

<Window x:Class="Test.Dialogs.DatatypesDialog"
        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"
        xmlns:local="clr-namespace:Test.Dialogs"
        mc:Ignorable="d"
        Title="DatatypesDialog" Width="301" Height="287" Background="Black" SizeToContent="WidthAndHeight" MinWidth="301" MinHeight="287" WindowStartupLocation="CenterOwner">
    <Grid Margin="0" >
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*" />
            <ColumnDefinition Width="1*" />
        </Grid.ColumnDefinitions>
        <ListBox Grid.Column="0" x:Name="lbDTypes" Margin="10,10,5,10" SelectionMode="Single" SelectionChanged="lbDTypes_SelectionChanged"/>
        <Grid Grid.Column="1" Margin="0,8,5,8" >
            <Grid.RowDefinitions>
                <RowDefinition Height="1*" />
                <RowDefinition Height="1*" />
                <RowDefinition Height="1*" />
                <RowDefinition Height="1*" />
                <RowDefinition Height="1*" />
                <RowDefinition Height="1*" />
                <RowDefinition Height="1*" />
                <RowDefinition Height="1*" />
                <RowDefinition Height="1*" />
                <RowDefinition Height="1*" />
            </Grid.RowDefinitions>
            <TextBox Grid.Row="0" x:Name="tbDType" Margin="5,2,5,2" TextWrapping="Wrap" Text="" />
            <Button Grid.Row="1" Margin="5,2,5,2" Content="New" Click="NewDType"   />
            <Button Grid.Row="2" Margin="5,2,5,2" Content="Modify" Click="EditDType"/>
            <Button Grid.Row="3" Margin="5,2,5,2" Content="Remove" Click="RemoveDType"/>
            <Separator Grid.Row="4" Margin="5,2,5,2"  />
            <Button Grid.Row="5" Margin="5,2,5,2" Content="Move Up" Click="MoveUpDType"  />
            <Button Grid.Row="6" Margin="5,2,5,2" Content="Move Down" Click="MoveDownDType" />
            <Separator Grid.Row="7" Margin="5,2,5,2" />
            <Button Grid.Row="8" Margin="5,2,5,2" Content="Save" Click="Save"/>
            <Button Grid.Row="9" Margin="5,2,5,2" Content="Close" Click="Close"/>
        </Grid>
    </Grid>
</Window>

属性 SizeToContent="WidthAndHeight" 应对此行为负责。删除 属性 或将其设置为另一个值("Manual""Width"),window 将不再适应列表框。