如何保持网格单元的高度和宽度相同

Cob*_*old 6 wpf grid height cell width

Grid调整大小时我需要保持单元格高度=宽度.

使用viewBox的工作代码:

  <Viewbox>
        <Grid>
            <Grid.RowDefinitions>
                    <RowDefinition Height="1*"/>
                    <RowDefinition Height="1*"/>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="Auto"/>
                    <ColumnDefinition Width="Auto"/>
                </Grid.ColumnDefinitions>
                <Label Grid.Row="0" Grid.Column="0" Background="Black" Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"></Label>
                <Label Grid.Row="1" Grid.Column="0" Background="Gray" Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"></Label>
                <Label Grid.Row="0" Grid.Column="1" Background="Gray" Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"></Label>
                <Label Grid.Row="1" Grid.Column="1" Background="Black" Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"></Label>
            </Grid>
        </Viewbox>
Run Code Online (Sandbox Code Playgroud)

感谢HB对于使用viewBox的想法!:)

H.B*_*.B. 9

执行此操作的"正确"方法可能是使用Grid控件的共享大小功能,但这可以防止拉伸整个网格.例如

<Grid Grid.IsSharedSizeScope="True">
    <Grid.ColumnDefinitions>
        <ColumnDefinition SharedSizeGroup="A"/>
        <ColumnDefinition SharedSizeGroup="A"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition SharedSizeGroup="A"/>
        <RowDefinition SharedSizeGroup="A"/>
    </Grid.RowDefinitions>
    <Label Grid.Row="0" Grid.Column="0" Background="Red"   Content="Lorem"/>
    <Label Grid.Row="1" Grid.Column="0" Background="White" Content="Lorem ipsum"/>
    <Label Grid.Row="0" Grid.Column="1" Background="White" Content="Lorem ipsum dolor"/>
    <Label Grid.Row="1" Grid.Column="1" Background="Red"   Content="Lorem ipsum dolor sit"/>
</Grid>
Run Code Online (Sandbox Code Playgroud)

可以把它放在一个Viewbox但是调整大小的行为可能不是你想要的,因为它缩放了内容.也许您可以找到一种方法使其在您的上下文中可用.


Mat*_*est 5

WPF提供了UniformGrid- 您可能会发现这对您尝试执行的操作更有帮助.这是一篇演示它的文章:http: //www.c-sharpcorner.com/UploadFile/yougerthen/308222008124636PM/3.aspx

为了保持正方形,只需将网格的Width属性绑定到自己的ActualHeight属性:

Width="{Binding RelativeSource={RelativeSource Self}, Path=ActualHeight}"
Run Code Online (Sandbox Code Playgroud)