简体   繁体   English

如何在XAML中构建具有平方中心单元的3x3网格

[英]How to build a 3x3 grid with squared center cell in XAML

I am trying to build a 3x3 grid with XAML (for a Windows Phone application) where the center cell should be a square. 我正在尝试使用XAML(用于Windows Phone应用程序)构建3x3网格,其中中心单元格应为正方形。 I have tried the following but it does not work: 我尝试了以下但它不起作用:

<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="5*" x:Name="centerColumnDefinition" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="{Binding ElementName=centerColumnDefinition, Path=ActualWidth}" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Canvas Grid.Row="1" Grid.Column="1">
        ...
    </Canvas>
</Grid>

Any suggestions for a working solution? 对工作解决方案的任何建议?

Greetings from Germany, 来自德国的问候,

Tobias 托比亚斯

Try this 尝试这个

<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition x:Name="centerColumnDefinition" 
                          Width="5*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
    <Rectangle x:Name="CenterRect"
               Grid.Row="1"
               Grid.Column="1"
               Height="{Binding ElementName=CenterRect,
                                Path=ActualWidth}"
               HorizontalAlignment="Stretch" />
</Grid>

It can be tricky to reference column and row definitions because they are not "real" objects in the visual tree. 引用列和行定义可能很棘手,因为它们不是可视树中的“真实”对象。 This method avoids the problem by using a separate object in the center cell that can be used to get the proper sizes. 此方法通过在中心单元格中使用可用于获取正确大小的单独对象来避免此问题。

You should be able to replace the rectangle with another type of control if you want, or just leave it and embed your content inside the rectangle. 如果需要,您应该可以使用其他类型的控件替换矩形,或者只是将其保留并将内容嵌入矩形内。

ActualHeight and ActualWidth are not set until the control is measured and arranged. 在测量和排列控件之前,不会设置ActualHeight和ActualWidth。 Usually there is nothing in InitializeComponent() that causes a measure, so you will need to set the Height of your rows after it's calculated. 通常,InitializeComponent()中没有任何内容会导致度量,因此您需要在计算后设置行的高度。 You can do the re-sizing on Loaded event. 您可以在Loaded事件上重新调整大小。

Source: https://stackoverflow.com/a/1695518/546896 资料来源: https//stackoverflow.com/a/1695518/546896

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM