百分比值能在XAML中使用吗?

36
在 HTML 中,可以使用 width="20%" 来设置宽度。当然,在 XAML 中是不允许这样做的。有没有人知道为什么,或者是否有一种方法可以在 XAML 中支持百分比值?
3个回答

77

网格(ColumnDefinitions和RowDefinitions)允许使用比例单位(除了固定像素和Auto),以下是2个例子:

<Grid.ColumnDefinitions>
  <ColumnDefinition Width="Auto" />
  <ColumnDefinition Width="20" />
  <ColumnDefinition Width="*" />
  <ColumnDefinition Width="*"/>
  <ColumnDefinition Width="*"/>
  <ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>

第一列将根据内容的大小调整宽度。下一列为20个设备无关像素宽度。网格剩余的宽度将在其余列之间平均分配。(100% / 4 = 每个列占25%)

<Grid.ColumnDefinitions>
  <ColumnDefinition Width="*" />
  <ColumnDefinition Width="4*"/>
  <ColumnDefinition Width="4*"/>
  <ColumnDefinition Width="*"/> 
</Grid.ColumnDefinitions>

这段代码将总 Grid 宽度分成了 10%,40%,40% 和 10% 的四列。


9
成比例的。 等同于1。你可以有分数单位。将所有数字相加,然后每个列宽度是其自身数字除以总数。如果其余列合计为80,那么20*将等于20%。 - foson
1
请注意,在数字4后面加上星号。当我第一次看到它时,我错过了它。我看到的是“4”,而不是“4*”。是我的眼睛有问题吗? - John Stock
对于我的Xamarin.Forms 4.6项目,使用*比例值设置所有宽度属性是有效的。例如:<Grid.ColumnDefinitions> <ColumnDefinition Width="20*" /> <ColumnDefinition Width="60*" /> <ColumnDefinition Width="20*" /> </Grid.ColumnDefinitions> - chri3g91

2
如果您没有使用网格,那么可以使用Xamarin.Essentials来获取实际的宽度/高度(以像素为单位),然后除以密度并乘以所需的尺寸。例如:
Convert.ToInt32(Math.Round(DeviceDisplay.MainDisplayInfo.Width / DeviceDisplay.MainDisplayInfo.Density * 0.9))

实际屏幕宽度(以像素为单位)/密度*所需百分比

我的示例是屏幕宽度的90%,您可以在Xaml中从VM绑定到此计算

Xaml

<StackLayout WidthRequest="{Binding PickerWidth}" BackgroundColor="AliceBlue">
    <Label Text="Test" HorizontalOptions="FillAndExpand"/>
</StackLayout>

VM

private int _pickerWidth;
public int PickerWidth
{
     get => _pickerWidth;
     set => SetProperty(ref _pickerWidth, value);
}

public void Init()
{
   PickerWidth = Convert.ToInt32(Math.Round(DeviceDisplay.MainDisplayInfo.Width / DeviceDisplay.MainDisplayInfo.Density * 0.9))
}

我刚开始在使用XF 4.8上运行的iOS和Android应用程序中使用它,可以正确地将弹出页面大小调整为可用屏幕宽度的90%。已在平板电脑和手机上进行了测试。

1

你最好采用编程方式来解决问题。

将一半屏幕大小分配给元素的示例:

var deviceScreenHeight = DeviceDisplay.MainDisplayInfo.Height;
view.HeightRequest = deviceScreenHeight * .5; 

限制在于它不能直接通过绑定到XAML应用,但可以轻松解决相关问题,并可分配给任何视图尺寸(当然)。始终要理解,像这样的简单计算是复杂应用的基础,因此可以轻松应用。请随意将其应用于继承类,该类根据任何百分比计算重载高度或宽度。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接