【问题标题】:Set grid size to windows size将网格大小设置为窗口大小
【发布时间】:2021-01-20 14:33:58
【问题描述】:

我有以下代码可以使网格完全适合窗口。 正如您在屏幕截图中看到的那样,网格在底部和右侧的窗口之外运行。你们知道为什么会这样吗?以及如何正确地做到这一点?

<Window x:Class="WpfApp1.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"
        Topmost="true"
        Background="Aqua"
        WindowStartupLocation="CenterScreen"
        DataContext="{Binding Main, Source={StaticResource Locator}}"
        Title="MainWindow" Height="500" Width="500">
    <Grid 
        Width="{Binding ActualWidth, RelativeSource = {RelativeSource AncestorType = {x:Type Window}}}" 
        Height="{Binding ActualHeight, RelativeSource ={RelativeSource AncestorType = {x:Type Window}}}">
        <Border Opacity=".9" BorderBrush="Blue" BorderThickness="2"/>
    </Grid>
</Window>

【问题讨论】:

  • 为什么要设置网格的宽度和高度?如果可能,尽量省略它们。

标签: wpf xaml grid window size


【解决方案1】:

如果绑定窗口的实际宽度和高度,Grid 将超过Window,因为内容区域小于窗口本身。移除绑定。如果您没有明确设置WidthHeightGrid 将自动调整大小以占用可用空间。

<Window x:Class="WpfApp1.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"
        Topmost="true"
        Background="Aqua"
        WindowStartupLocation="CenterScreen"
        DataContext="{Binding Main, Source={StaticResource Locator}}"
        Title="MainWindow" Height="500" Width="500">
    <Grid>
        <Border Opacity=".9" BorderBrush="Blue" BorderThickness="2"/>
    </Grid>
</Window>

【讨论】:

  • 谢谢。那我就省略了。如果我想在整个窗口上调整另一个元素的大小,比如在层次结构下方的图像,那么我怎么能把它适应实际的内容大小呢?
  • @dasd-431 这真的取决于层次结构的样子,对此没有一般的答案。
猜你喜欢
  • 2012-08-31
  • 1970-01-01
  • 2013-10-05
  • 2019-02-25
  • 2022-06-18
  • 2019-04-06
  • 1970-01-01
  • 1970-01-01
  • 2023-04-11
相关资源
最近更新 更多