WPF 网格设置为 Window 的实际宽度,发生裁剪

WPF Grid Set To ActualWidth of Window, clipping occurs

我在这里找到了关于如何确保在调整 Window 大小时,其中的网格也相应调整大小的答案。我面临的问题是我在网格内部有一个 StackPanel,"X"(关闭)按钮没有完全显示(只有大约一半在 Window.

代码如下:

<Canvas>
        <Grid Width="{Binding ActualWidth,RelativeSource={RelativeSource AncestorType={x:Type Window}}}">
            <Grid.RowDefinitions>
                <RowDefinition></RowDefinition>
                <RowDefinition></RowDefinition>
                <RowDefinition></RowDefinition>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <StackPanel Orientation="Horizontal" Grid.Row="0" FlowDirection="RightToLeft" HorizontalAlignment="Right" Background="#FF2B2B2B" Margin="0,0,20,0">
                <Button FontFamily="Marlett" FontSize="13" VerticalAlignment="Top" Foreground="White" Command="{x:Static SystemCommands.CloseWindowCommand}" Background="#FF2B2B2B">r</Button>
                <Button FontFamily="Marlett" FontSize="13" VerticalAlignment="Top" Foreground="White" Command="{x:Static SystemCommands.MaximizeWindowCommand}" Background="#FF2B2B2B">1</Button>
                <Button FontFamily="Marlett" FontSize="13" VerticalAlignment="Top" Foreground="White" Command="{x:Static SystemCommands.MinimizeWindowCommand}" Background="#FF2B2B2B">0</Button>
            </StackPanel>
        </Grid>
</Canvas>

如 HighCore 所说,删除 Canvas 并为第一行放置一个额外的网格。 这应该是工作。查看 RowDefinitions 和 ColumnDefinitions 中的高度和宽度。

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

    <Grid Grid.Row="0" Background="CadetBlue">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>

        <TextBlock Text="title" TextAlignment="Center"/>

        <StackPanel Grid.Row="0" Grid.Column="1" Orientation="Horizontal"  Background="#FF2B2B2B">
            <Button FontFamily="Marlett" FontSize="13" VerticalAlignment="Top" Foreground="White" Command="{x:Static SystemCommands.CloseWindowCommand}" Background="#FF2B2B2B">r</Button>
            <Button FontFamily="Marlett" FontSize="13" VerticalAlignment="Top" Foreground="White" Command="{x:Static SystemCommands.MaximizeWindowCommand}" Background="#FF2B2B2B">1</Button>
            <Button FontFamily="Marlett" FontSize="13" VerticalAlignment="Top" Foreground="White" Command="{x:Static SystemCommands.MinimizeWindowCommand}" Background="#FF2B2B2B">0</Button>
        </StackPanel>
    </Grid>

</Grid>