5
當試圖使用在Xamarin.Forms控制的Height
和Width
性質,都返回-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;
這對於包含動態文本的標籤居中也很有用!隨着文本大小的增加/減少,相對佈局將自動重新計算其寬度並保持標籤居中! –
CaptainXamtastic在Xamarin Forms中的回答也很好地解釋了這一點:https://forums.xamarin.com/discussion/22902/how-to-add-a-label-to-a-relative-layout-and - 它橫向中心 –
有沒有辦法在XAML中做到這一點? –