【发布时间】:2020-05-14 09:54:15
【问题描述】:
我已经为这个问题苦苦挣扎了太久。应该很简单的东西.. 我正在 Xamarin.Forms 中制作一个井字游戏应用程序。板本身包含 3x3 按钮,每个按钮都放置在自己的网格单元中。我有 3 个水平单元格和 3 个垂直单元格。
包含这些单元格的网格被放置在另一个网格的网格行中。如图所示,板子的水平部分会自动扩展,占据整个屏幕宽度。但我希望按钮/网格行的高度完全相同,以便它们创建一个完美的正方形。我可以通过在使用 HeightRequest = someValue 创建按钮时硬编码一个值来做到这一点,但我想将它绑定到按钮/gridColumn 的宽度,以便无论您在什么设备上运行它都看起来不错。
在这个例子中,我硬编码了 Grid 行的高度。如您所见,它在 iPhone 上看起来不错,但在 iPad 上却很糟糕,因为它更大的显示屏和更高的像素数量。如果我能把高度和宽度一样就好了。
网格是用 XAML 制作的:
<Grid x:Name="rootGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="70" />
<RowDefinition Height="60" />
<RowDefinition Height="400"/>
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Label Text="Tic Tac Toe" HorizontalOptions="Center" VerticalOptions="StartAndExpand" Padding="0,50,0,0" FontFamily="Arial" FontAttributes="Bold" FontSize="Large" TextColor="#FFFFFF" Grid.Row="0" Grid.Column="0"/>
<Grid Grid.Row="1" Margin="0,20,0,0" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label HorizontalTextAlignment="Center" Text="X: 0 points" Grid.Column="0" TextColor="#FFFFFF" IsVisible="True"></Label>
<Label HorizontalTextAlignment="Center" Text="O: 0 points" Grid.Column="1" TextColor="#FFFFFF" IsVisible="True"></Label>
</Grid>
<Grid Grid.Row="2" x:Name="theBoard">
<Grid.ColumnDefinitions>
<ColumnDefinition x:Name="col1" Width="*" />
<ColumnDefinition x:Name="col2" Width="*" />
<ColumnDefinition x:Name="col3" Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
<!--<RowDefinition BindingContext="{x:Reference Name=col1}" Height="{Binding Path=Width}"/>-->
</Grid.RowDefinitions>
</Grid>
</Grid>
按钮是这样添加的:
private void CreateFields()
{
// Iterate through the rows
for (int i = 0; i < fields.GetLength(1); i++)
{
// Iterate through the columns
for (int j = 0; j < fields.GetLength(0); j++)
{
Button field = new Button()
{
BackgroundColor = Color.WhiteSmoke,
};
// Adds the new button to the two dimensional array
fields[i, j] = field;
theBoard.Children.Add(field, j, i);
}
}
//Console.WriteLine("The current width of the button is: " + fields[0,0].Width);
//Console.WriteLine("The current height of the button is: " + fields[0,0].Height);
//Console.WriteLine("The current width of the column is: " + col1.Width);
// Console.WriteLine("The current height of the column is: " + row1.Height);
}
我真的希望有人能够帮助我。它必须是一些我忘记的简单细节。 在 WPF 中,我曾经有一个叫做“ActualWidth”的东西,但这里似乎不是这样。
【问题讨论】:
-
我猜你可以使用 XF CollectionView 这不是让一切变得更容易吗!
-
您尝试过 RelativLayout。它非常适合您的需要。我已经为此添加了一个答案,请查看。
-
另外,如果您愿意,我可以使用
GridLayout 为您提供解决方案,如果您希望根据区域适合哪个!
标签: c# xaml xamarin xamarin.forms binding