如何在 .Net Maui 中创建第一个单元格为正方形的网格?

问题描述 投票:0回答:2

我想创建一个网格,其第一个单元格为正方形,即其高度等于其宽度,而宽度由屏幕宽度决定。 我在想像下面这样的东西,但它不起作用。

<Grid RowDefinitions ="{DeviceDisplay.Current.MainDisplayInfo.Width}, *">
... ...
</Grid>
.net xaml grid maui
2个回答
1
投票

是的,您可以通过代码实现这一点。

我创建了一个demo,你可以参考以下代码:

public class GridPageCS : ContentPage
{
    public GridPageCS()
    {
        Grid grid = new Grid
        {
            RowDefinitions =
            {
                new RowDefinition { Height = new GridLength(DeviceDisplay.Current.MainDisplayInfo.Width, GridUnitType.Star) },
                new RowDefinition { Height = new GridLength(100) }
            },
            ColumnDefinitions =
            {
                new ColumnDefinition()
            }
        };

        grid.Children.Add(new BoxView
        {
            Color = Colors.Green
        });
        grid.Children.Add(new Label
        {
            Text = "Row 0, Column 0",
            HorizontalOptions = LayoutOptions.Center,
            VerticalOptions = LayoutOptions.Center
        });

        Title = "Basic Grid demo";
        Content = grid;
    }
}

0
投票

如果您想要一个完美的方形单元格,并且无论纵向/横向尺寸如何,都填充剩余部分,我们可以使用视图模型来提供帮助。

<!-- MainPage.xaml -->
<Grid Width="{Binding GridWidth, Mode=OneWayToSource}"
      Height="{Binding GridHeight, Mode=OneWayToSource}">
    <Grid.RowDefinitions>
        <RowDefinition Height="{Binding SquareCellSize}"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="{Binding SquareCellSize}"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Rectangle x:Name="squareCell" Fill="LightSteelBlue"/>
    <Rectangle x:Name="nextCell" Fill="Orange" Grid.Row="{Binding NextRow}" Grid.Column="{Binding NextColumn}"/>
</Grid>

在上面,我们使用

OneWayToSource
绑定来检索父级
Width
Height
Grid
。我们用它来计算方形单元的尺寸以及下一个单元的位置(即它可能位于方形单元的右侧,也可能位于底部)。

public partial class MainViewModel : ObservableObject
{
    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(SquareCellSize))]
    [NotifyPropertyChangedFor(nameof(NextRow))]
    [NotifyPropertyChangedFor(nameof(NextColumn))]
    private double _gridWidth = 100;

    [ObservableProperty]
    [NotifyPropertyChangedFor(nameof(SquareCellSize))]
    [NotifyPropertyChangedFor(nameof(NextRow))]
    [NotifyPropertyChangedFor(nameof(NextColumn))]
    private double _gridHeight = 100;

    public double SquareCellSize => Math.Max(Math.Min(GridWidth, GridHeight), 1);
    public int NextRow => GridHeight >= GridWidth ? 1 : 0;
    public int NextColumn => GridHeight >= GridWidth ? 0 : 1;
}
© www.soinside.com 2019 - 2024. All rights reserved.