Dlaczego Xamarin.Forms zwracają -1 dla Height
i Width
?
Xamarin.Forms zwraca -1 jako wartość domyślną dla tych właściwości i pozostaje -1, dopóki Xamarin.Form nie utworzy formantu natywnego, np. UIButton i dodaje natywną kontrolę do układu.
W tym linkiem można zobaczyć Xamarin.Forms kod źródłowy powracającego -1
jako wartość domyślna: https://github.com/xamarin/Xamarin.Forms/blob/master/Xamarin.Forms.Core/VisualElement.cs
Najlepszy sposób na wykorzystanie układów względem Ograniczenie Wyświetleń
użyć Func
dynamicznie pobierać Width
i Height
właściwości
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;

Dzięki @BrewMate za nauczenie mnie tej sztuczki!
Znakomicie nadaje się również do centrowania etykiet zawierających tekst dynamiczny! Wraz ze wzrostem/spadkiem tekstu Układ Względny automatycznie przeliczy jego szerokość i utrzyma wyśrodkowanie etykiety! –
Odpowiedź CaptainXamtastic w Xamarin Forms również świetnie wyjaśnia to: https://forums.xamarin.com/discussion/22902/how-to-add-a-label-to-a-relative-layout-and -center-it-horizontally –
Czy można to zrobić w XAML? –