2016-12-02 1 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을 반환하고 Xamarin.Forms가 네이티브 컨트롤을 만들 때까지 -1을 유지합니다. UIButton을 생성하고 레이아웃에 네이티브 컨트롤을 추가합니다. 조회수

사용하십시오 Func 동적를 검색을 제한 할 상대 레이아웃을 사용하는 https://github.com/xamarin/Xamarin.Forms/blob/master/Xamarin.Forms.Core/VisualElement.cs

가장 좋은 방법은이 링크에서

, 당신은 기본 값으로 -1을 반환하는 Xamarin.Forms 소스 코드를 볼 수 있습니다 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

Xamarin Forms의 CaptainXamtastic의 답은 다음을 설명하는 훌륭한 작업입니다. https://forums.xamarin.com/discussion/22902/how-to-add-a-label-to-a-relative-layout-and -center-it-horizontally –

+11

XAML에서이 작업을 수행 할 수있는 방법이 있습니까? –

관련 문제