2016-12-02 36 views
5

當試圖使用在Xamarin.Forms控制的HeightWidth性質,都返回-1,它會導致相對佈局顯示在屏幕上偏離中心。Xamarin.Forms:如何使用相對佈局居中視圖? `Width`和`Height`返回-1

var mainLayout = new RelativeLayout(); 

//Add the Switch to the center of the screen 
mainLayout.Children.Add(mySwitch, 
    Constraint.RelativeToParent(parent => parent.Width/2 - mySwitch.Width/2), 
    Constraint.RelativeToParent(parent => parent.Height/2 - mySwitch.Height/2)); 

//Add a Label below the switch 
mainLayout.Children.Add(switchLabel, 
    Constraint.RelativeToParent(parent => parent.Width/2 - switchLabel.Width/2), 
    Constraint.RelativeToView(mySwitch, (parent, view) => view.Y + mySwitch.Height + 10)); 

Content = mainLayout; 

enter image description here

回答

14

爲什麼Xamarin.Forms返回-1爲HeightWidth

Xamarin.Forms返回-1作爲這些屬性的默認值,它仍然-1直到Xamarin.Forms創建本地控制,例如UIButton,並將該本地控制添加到佈局。

在這個環節,你可以看到Xamarin.Forms源代碼返回-1作爲默認值: https://github.com/xamarin/Xamarin.Forms/blob/master/Xamarin.Forms.Core/VisualElement.cs

最佳方式使用相對佈局,以限制瀏覽

使用Func動態檢索WidthHeight性質

var mainLayout = new RelativeLayout(); 

Func<RelativeLayout, double> getSwitchWidth = (parent) => mySwitch.Measure(parent.Width, parent.Height).Request.Width; 
Func<RelativeLayout, double> getSwitchHeight = (parent) => mySwitch.Measure(parent.Width, parent.Height).Request.Height; 
Func<RelativeLayout, double> getLabelWidth = (parent) => switchLabel.Measure(parent.Width, parent.Height).Request.Width; 
Func<RelativeLayout, double> getLabelHeight = (parent) => switchLabel.Measure(parent.Width, parent.Height).Request.Height; 

//Add the Switch to the center of the screen 
mainLayout.Children.Add(mySwitch, 
    Constraint.RelativeToParent(parent => parent.Width/2 - getSwitchWidth(parent)/ 2), 
    Constraint.RelativeToParent(parent => parent.Height/2 - getSwitchHeight(parent)/2)); 

//Add a Label below the switch 
mainLayout.Children.Add(switchLabel, 
    Constraint.RelativeToParent(parent => parent.Width/2 - getLabelWidth(parent)/2), 
    Constraint.RelativeToView(mySwitch, (parent, view) => view.Y + getSwitchHeight(parent) + 10)); 

Content = mainLayout; 

enter image description here

感謝@BrewMate教我這招!

+1

這對於包含動態文本的標籤居中也很有用!隨着文本大小的增加/減少,相對佈局將自動重新計算其寬度並保持標籤居中! –

+0

CaptainXamtastic在Xamarin Forms中的回答也很好地解釋了這一點:https://forums.xamarin.com/discussion/22902/how-to-add-a-label-to-a-relative-layout-and - 它橫向中心 –

+11

有沒有辦法在XAML中做到這一點? –

相關問題