在 HTML 中,可以使用 width="20%" 来设置宽度。当然,在 XAML 中是不允许这样做的。有没有人知道为什么,或者是否有一种方法可以在 XAML 中支持百分比值?
网格(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% 的四列。
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))
}
你最好采用编程方式来解决问题。
将一半屏幕大小分配给元素的示例:
var deviceScreenHeight = DeviceDisplay.MainDisplayInfo.Height;
view.HeightRequest = deviceScreenHeight * .5;