我找不到获得Width和Height of a Xamarin.Forms.View的方法。
我有一个目标:
public class SquareLayout : View
{
public static readonly BindableProperty ScalingBaseProperty =
BindableProperty.Create(nameof(ScalingBase), typeof(ScalingBaseType), typeof(SquareLayout), ScalingBaseType.Average,
propertyChanged: OnScalingBasePropertyChanged);
public ScalingBaseType ScalingBase
{
get { return (ScalingBaseType)GetValue(ScalingBaseProperty); }
set { SetValue(ScalingBaseProperty, value); }
}
public enum ScalingBaseType
{
Average,
Height,
Width
}
public static void OnScalingBasePropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
SquareLayout sq = ((SquareLayout)bindable);
Debug.WriteLine("|Width = {0}|Height = {1}|", sq.Bounds.Width, sq.Bounds.Height);
switch (sq.ScalingBase)
{
case ScalingBaseType.Average:
double size = (sq.Bounds.Width + sq.Bounds.Height) / 2;
sq.WidthRequest = size;
sq.HeightRequest = size;
break;
case ScalingBaseType.Height:
sq.WidthRequest = sq.Bounds.Height;
break;
case ScalingBaseType.Width:
sq.HeightRequest = sq.Bounds.Width;
break;
}
Debug.WriteLine("|Width = {0}|Height = {1}|", sq.Bounds.Width, sq.Bounds.Height);
}
}基本上,您可以在这个SquareLayout的某个位置声明,然后,根据一个Enum,将布局调整为Square。
那么,我就有了这个XAML部件
<ContentPage.Content>
<AbsoluteLayout BackgroundColor="White">
...
<AbsoluteLayout x:Name="ToolsLayout" BackgroundColor="Red"
AbsoluteLayout.LayoutBounds="0.5, 0.05, 0.9, 0.075"
AbsoluteLayout.LayoutFlags="All">
<control:SquareLayout BackgroundColor="White" ScalingBase="Height"
AbsoluteLayout.LayoutBounds="0, 0.5, 0.1, 1"
AbsoluteLayout.LayoutFlags="All">
</control:SquareLayout>
<control:SquareLayout BackgroundColor="White" ScalingBase="Height"
AbsoluteLayout.LayoutBounds="1, 0.5, 0.1, 1"
AbsoluteLayout.LayoutFlags="All">
</control:SquareLayout>
</AbsoluteLayout>
...
</AbsoluteLayout>
</ContentPage.Content>这会给我一个有两个Square的Square。但什么都没有!
我试着显示Width和Height,但什么也没有。我试过了Bounds,就像你在这个例子中看到的一样,但是再也没有了。
我得到的唯一值是-1。
有人能帮我吗?提前感谢!
发布于 2017-08-24 05:09:27
Xamarin对于新手的文档非常少,花了一些时间来解决这个问题,基本上在设计期间宽度和高度属性的默认值为-1,这表示自动,因此在设计期间无法知道这些值是什么,因此您需要使用“events”来获得宽度和高度属性,在这种情况下,在运行时设置布局界限时,需要使用SizeChanged事件。
在xaml代码背后,使用此事件获取布局的宽度和高度,我使用了lambda函数,这可以通过多种方式实现--我觉得这个方法很简单。
yourlayout.SizeChanged+=(sender,e)=>
{
//Add your child objects here and set its values using yourlayout.Height etc
};与在此函数中添加子函数不同,您可以使用它返回值并使用该值。
注意:我不确定这是否是MVVM的最佳实践。
https://stackoverflow.com/questions/39950086
复制相似问题