Xamarin.Forms StackLayout
de Xamarin.Forms= StackLayout" data-linktype="relative-path">
Xamarin.Forms
StackLayout" title=" Xamarin.Forms StackLayout" data-linktype="relative-path"/>
Organiza StackLayout las vistas secundarias en una pila unidimensional, ya sea horizontal o verticalmente. De forma predeterminada, las vistas StackLayout están orientadas verticalmente. Además, se StackLayout puede usar como un diseño primario que contiene otros diseños secundarios.
La clase StackLayout define las propiedades siguientes:
- _StackLayout_Orientation" data-linktype="absolute-path">, de tipo , representa la dirección en la que se sitúan las
OrientationStackOrientationvistas secundarias. El valor predeterminado de esta propiedad esVertical. - Xamarin_Forms _StackLayout_Spacing" data-linktype="absolute-path">, de tipo , indica la cantidad de espacio entre
Spacingcada vistadoublesecundaria. El valor predeterminado de esta propiedad es seis unidades independientes del dispositivo.
Estas propiedades están copiadas por objetos , lo que significa que las propiedades pueden ser destinos de enlaces BindableProperty de datos y con estilo.
La StackLayout clase se deriva de la clase , que define una propiedad de tipo Layout<T>ChildrenIList<T> . La propiedad es de la clase y, por tanto, no es necesario establecer ChildrenContentPropertyLayout<T> explícitamente desde XAML.
Sugerencia
Para obtener el mejor rendimiento de diseño posible, siga las instrucciones de Optimización del rendimiento del diseño.
Orientación vertical
En el código XAML siguiente se muestra cómo crear un elemento orientado verticalmente StackLayout que contiene diferentes vistas secundarias:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="StackLayoutDemos.Views.VerticalStackLayoutPage"
Title="Vertical StackLayout demo">
<StackLayout Margin="20">
<Label Text="Primary colors" />
<BoxView Color="Red" />
<BoxView Color="Yellow" />
<BoxView Color="Blue" />
<Label Text="Secondary colors" />
<BoxView Color="Green" />
<BoxView Color="Orange" />
<BoxView Color="Purple" />
</StackLayout>
</ContentPage>
En este ejemplo se crea un objeto vertical StackLayout que contiene objetos y LabelBoxView . De forma predeterminada, hay seis unidades de espacio independientes del dispositivo entre las vistas secundarias:
El código de C# equivalente es el siguiente:
public class VerticalStackLayoutPageCS : ContentPage
{
public VerticalStackLayoutPageCS()
{
Title = "Vertical StackLayout demo";
Content = new StackLayout
{
Margin = new Thickness(20),
Children =
{
new Label { Text = "Primary colors" },
new BoxView { Color = Color.Red },
new BoxView { Color = Color.Yellow },
new BoxView { Color = Color.Blue },
new Label { Text = "Secondary colors" },
new BoxView { Color = Color.Green },
new BoxView { Color = Color.Orange },
new BoxView { Color = Color.Purple }
}
};
}
}
Nota:
El valor de la propiedad Xamarin_Forms _View_Margin" data-linktype="absolute-path">representa la distancia entre un elemento y sus Margin elementos adyacentes. Para obtener más información, vea Márgenes y relleno.
Orientación horizontal
El código XAML siguiente muestra cómo crear una propiedad orientada horizontalmente estableciendo su propiedad StackLayout Xamarin_Forms StackLayout _StackLayout_Orientation" data-linktype="absolute-path">Orientation en Horizontal :
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="StackLayoutDemos.Views.HorizontalStackLayoutPage"
Title="Horizontal StackLayout demo">
<StackLayout Margin="20"
Orientation="Horizontal"
HorizontalOptions="Center">
<BoxView Color="Red" />
<BoxView Color="Yellow" />
<BoxView Color="Blue" />
<BoxView Color="Green" />
<BoxView Color="Orange" />
<BoxView Color="Purple" />
</StackLayout>
</ContentPage>
En este ejemplo se crea un objeto que StackLayout contiene objetos horizontales, con seis unidades de espacio independientes del dispositivo BoxView entre las vistas secundarias:
El código de C# equivalente es el siguiente:
public HorizontalStackLayoutPageCS()
{
Title = "Horizontal StackLayout demo";
Content = new StackLayout
{
Margin = new Thickness(20),
Orientation = StackOrientation.Horizontal,
HorizontalOptions = LayoutOptions.Center,
Children =
{
new BoxView { Color = Color.Red },
new BoxView { Color = Color.Yellow },
new BoxView { Color = Color.Blue },
new BoxView { Color = Color.Green },
new BoxView { Color = Color.Orange },
new BoxView { Color = Color.Purple }
}
};
}
Espacio entre vistas secundarias
El espaciado entre las vistas secundarias de un elemento se puede cambiar estableciendo la propiedad StackLayoutStackLayout Xamarin_Forms _StackLayout_Spacing" data-linktype="absolute-path">Spacing en un double valor:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="StackLayoutDemos.Views.StackLayoutSpacingPage"
Title="StackLayout Spacing demo">
<StackLayout Margin="20"
Spacing="0">
<Label Text="Primary colors" />
<BoxView Color="Red" />
<BoxView Color="Yellow" />
<BoxView Color="Blue" />
<Label Text="Secondary colors" />
<BoxView Color="Green" />
<BoxView Color="Orange" />
<BoxView Color="Purple" />
</StackLayout>
</ContentPage>
En este ejemplo se crea un objeto vertical StackLayout que contiene objetos y que no tienen espaciado entre LabelBoxView ellos:
pantalla de un objeto
espaciado
Sugerencia
La Xamarin_Forms _StackLayout_Spacing" data-linktype="absolute-path">se puede establecer en valores negativos para que las vistas secundarias se Spacing superpongan.
El código de C# equivalente es el siguiente:
public class StackLayoutSpacingPageCS : ContentPage
{
public StackLayoutSpacingPageCS()
{
Title = "StackLayout Spacing demo";
Content = new StackLayout
{
Margin = new Thickness(20),
Spacing = 0,
Children =
{
new Label { Text = "Primary colors" },
new BoxView { Color = Color.Red },
new BoxView { Color = Color.Yellow },
new BoxView { Color = Color.Blue },
new Label { Text = "Secondary colors" },
new BoxView { Color = Color.Green },
new BoxView { Color = Color.Orange },
new BoxView { Color = Color.Purple }
}
};
}
}
Posición y tamaño de las vistas secundarias
El tamaño y la posición de las vistas secundarias dentro de depende de los valores de las propiedades StackLayoutStackLayout data-linktype="absolute-path">y HeightRequest Xamarin_Forms _VisualElement_WidthRequest" data-linktype="absolute-path">y los valores de sus propiedades WidthRequest Xamarin_Forms HeightRequest _View_HorizontalOptions" data-linktype="absolute-path">HorizontalOptions y Xamarin_Forms _VisualElement_HeightRequest Xamarin_Forms _View_VerticalOptions" data-linktype="absolute-path">VerticalOptions propiedades. En un StackLayout vertical, las vistas secundarias se expanden para rellenar el ancho disponible cuando su tamaño no se establece explícitamente. De forma similar, en un horizontal, las vistas secundarias se expanden para rellenar el alto disponible StackLayout cuando su tamaño no se establece explícitamente.
El Xamarin_Forms _View_HorizontalOptions" data-linktype="absolute-path">HorizontalOptions and Xamarin_Forms HorizontalOptions _View_VerticalOptions" data-linktype="absolute-path">properties of a , and its child views, can be set to fields from the VerticalOptionsStackLayoutLayoutOptions struct, which encapsulates two layout preferences:
- La alineación determina la posición y el tamaño de una vista secundaria dentro de su diseño primario.
- Expansión indica si la vista secundaria debe usar espacio adicional, si está disponible.
Sugerencia
No establezca las propiedades Xamarin_Forms _View_HorizontalOptions" data-linktype="absolute-path">HorizontalOptions and Xamarin_Forms HorizontalOptions _View_VerticalOptions" data-linktype="absolute-path">VerticalOptions de a StackLayout menos que sea necesario. Los valores predeterminados de LayoutOptions.Fill y LayoutOptions.FillAndExpand permiten la optimización de diseño óptima. Cambiar estas propiedades tiene un costo y consume memoria, incluso al volver a establecerlas en los valores predeterminados.
Alineación
En el ejemplo xaml siguiente se establecen las preferencias de alineación en cada vista secundaria de StackLayout :
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="StackLayoutDemos.Views.AlignmentPage"
Title="Alignment demo">
<StackLayout Margin="20">
<Label Text="Start"
BackgroundColor="Gray"
HorizontalOptions="Start" />
<Label Text="Center"
BackgroundColor="Gray"
HorizontalOptions="Center" />
<Label Text="End"
BackgroundColor="Gray"
HorizontalOptions="End" />
<Label Text="Fill"
BackgroundColor="Gray"
HorizontalOptions="Fill" />
</StackLayout>
</ContentPage>
En este ejemplo, las preferencias de alineación se establecen en los Label objetos para controlar su posición dentro de StackLayout . Los Start campos , , y se usan para definir la CenterEndFill alineación de los objetos dentro del elemento primario LabelStackLayout :
de pantalla de stackLayout con opciones
Un elemento StackLayout solo respeta las preferencias de alineación de las vistas secundarias que tienen la dirección opuesta a la orientación del StackLayout. Por lo tanto, las vistas secundarias del objeto orientado verticalmente establecen sus propiedades LabelStackLayout Xamarin_Forms Label _View_HorizontalOptions" data-linktype="absolute-path">HorizontalOptions en uno de los campos de alineación:
Start, que coloca enLabelel lado izquierdo deStackLayout.Center, que centraLabelen elStackLayout.End, que coloca elLabelen el lado derecho deStackLayout.Fill, que garantiza queLabelllena el ancho delStackLayout.
El código de C# equivalente es el siguiente:
public class AlignmentPageCS : ContentPage
{
public AlignmentPageCS()
{
Title = "Alignment demo";
Content = new StackLayout
{
Margin = new Thickness(20),
Children =
{
new Label { Text = "Start", BackgroundColor = Color.Gray, HorizontalOptions = LayoutOptions.Start },
new Label { Text = "Center", BackgroundColor = Color.Gray, HorizontalOptions = LayoutOptions.Center },
new Label { Text = "End", BackgroundColor = Color.Gray, HorizontalOptions = LayoutOptions.End },
new Label { Text = "Fill", BackgroundColor = Color.Gray, HorizontalOptions = LayoutOptions.Fill }
}
};
}
}
Expansión
En el ejemplo de XAML siguiente se establecen las preferencias de expansión Label en cada en StackLayout :
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="StackLayoutDemos.Views.ExpansionPage"
Title="Expansion demo">
<StackLayout Margin="20">
<BoxView BackgroundColor="Red"
HeightRequest="1" />
<Label Text="Start"
BackgroundColor="Gray"
VerticalOptions="StartAndExpand" />
<BoxView BackgroundColor="Red"
HeightRequest="1" />
<Label Text="Center"
BackgroundColor="Gray"
VerticalOptions="CenterAndExpand" />
<BoxView BackgroundColor="Red"
HeightRequest="1" />
<Label Text="End"
BackgroundColor="Gray"
VerticalOptions="EndAndExpand" />
<BoxView BackgroundColor="Red"
HeightRequest="1" />
<Label Text="Fill"
BackgroundColor="Gray"
VerticalOptions="FillAndExpand" />
<BoxView BackgroundColor="Red"
HeightRequest="1" />
</StackLayout>
</ContentPage>
En este ejemplo, las preferencias de expansión se establecen en Label los objetos para controlar su tamaño dentro de StackLayout . Los campos , , y se usan para definir la preferencia de alineación y si ocupará más espacio si StartAndExpand está disponible dentro del elemento primario CenterAndExpandEndAndExpandFillAndExpandLabelStackLayout :
de pantalla de un objeto StackLayout con opciones
Un elemento StackLayout solo puede expandir las vistas secundarias en la dirección de su orientación. Por lo tanto, el orientado verticalmente puede expandir las vistas secundarias que establecen sus propiedades StackLayoutLabel Xamarin_Forms StackLayout _View_VerticalOptions" data-linktype="absolute-path">VerticalOptions en uno de los campos de expansión. Esto significa que, para la alineación vertical, cada Label ocupa la misma cantidad de espacio en el StackLayout. Sin embargo, solo la propiedad final , que establece su Xamarin_Forms LabelLabel _View_VerticalOptions" data-linktype="absolute-path">en VerticalOptions tiene un tamaño FillAndExpand diferente.
Sugerencia
Al usar , asegúrese de que solo una vista secundaria está establecida en StackLayout Xamarin_Forms StackLayout _LayoutOptions_Expands" data-linktype="absolute-path">LayoutOptions.Expands . Esta propiedad garantiza que el elemento secundario especificado ocupa el mayor espacio que el StackLayout puede asignarle y es poco rentable realizar estos cálculos más de una vez.
El código de C# equivalente es el siguiente:
public ExpansionPageCS()
{
Title = "Expansion demo";
Content = new StackLayout
{
Margin = new Thickness(20),
Children =
{
new BoxView { BackgroundColor = Color.Red, HeightRequest = 1 },
new Label { Text = "StartAndExpand", BackgroundColor = Color.Gray, VerticalOptions = LayoutOptions.StartAndExpand },
new BoxView { BackgroundColor = Color.Red, HeightRequest = 1 },
new Label { Text = "CenterAndExpand", BackgroundColor = Color.Gray, VerticalOptions = LayoutOptions.CenterAndExpand },
new BoxView { BackgroundColor = Color.Red, HeightRequest = 1 },
new Label { Text = "EndAndExpand", BackgroundColor = Color.Gray, VerticalOptions = LayoutOptions.EndAndExpand },
new BoxView { BackgroundColor = Color.Red, HeightRequest = 1 },
new Label { Text = "FillAndExpand", BackgroundColor = Color.Gray, VerticalOptions = LayoutOptions.FillAndExpand },
new BoxView { BackgroundColor = Color.Red, HeightRequest = 1 }
}
};
}
Importante
Cuando se usa todo el espacio de un elemento StackLayout, las preferencias de expansión no tienen ningún efecto.
Para obtener más información sobre la alineación y la expansión, vea Layout Options in Xamarin.Forms .
Objetos StackLayout anidados
Se StackLayout puede usar como un diseño primario que contiene objetos secundarios StackLayout anidados u otros diseños secundarios.
El código XAML siguiente muestra un ejemplo de anidamiento de StackLayout objetos:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="StackLayoutDemos.Views.CombinedStackLayoutPage"
Title="Combined StackLayouts demo">
<StackLayout Margin="20">
...
<Frame BorderColor="Black"
Padding="5">
<StackLayout Orientation="Horizontal"
Spacing="15">
<BoxView Color="Red" />
<Label Text="Red"
FontSize="Large"
VerticalOptions="Center" />
</StackLayout>
</Frame>
<Frame BorderColor="Black"
Padding="5">
<StackLayout Orientation="Horizontal"
Spacing="15">
<BoxView Color="Yellow" />
<Label Text="Yellow"
FontSize="Large"
VerticalOptions="Center" />
</StackLayout>
</Frame>
<Frame BorderColor="Black"
Padding="5">
<StackLayout Orientation="Horizontal"
Spacing="15">
<BoxView Color="Blue" />
<Label Text="Blue"
FontSize="Large"
VerticalOptions="Center" />
</StackLayout>
</Frame>
...
</StackLayout>
</ContentPage>
En este ejemplo, el elemento primario StackLayout contiene objetos StackLayout anidados dentro de objetos Frame . El elemento StackLayout primario está orientado verticalmente, mientras que los objetos StackLayout secundarios están orientados horizontalmente:
Importante
Cuanto más se StackLayout anidan objetos y otros diseños, más impacto tendrán los diseños anidados en el rendimiento. Para obtener más información, vea Elegir el diseño correcto.
El código de C# equivalente es el siguiente:
public class CombinedStackLayoutPageCS : ContentPage
{
public CombinedStackLayoutPageCS()
{
Title = "Combined StackLayouts demo";
Content = new StackLayout
{
Margin = new Thickness(20),
Children =
{
new Label { Text = "Primary colors" },
new Frame
{
BorderColor = Color.Black,
Padding = new Thickness(5),
Content = new StackLayout
{
Orientation = StackOrientation.Horizontal,
Spacing = 15,
Children =
{
new BoxView { Color = Color.Red },
new Label { Text = "Red", FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)), VerticalOptions = LayoutOptions.Center }
}
}
},
new Frame
{
BorderColor = Color.Black,
Padding = new Thickness(5),
Content = new StackLayout
{
Orientation = StackOrientation.Horizontal,
Spacing = 15,
Children =
{
new BoxView { Color = Color.Yellow },
new Label { Text = "Yellow", FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)), VerticalOptions = LayoutOptions.Center }
}
}
},
new Frame
{
BorderColor = Color.Black,
Padding = new Thickness(5),
Content = new StackLayout
{
Orientation = StackOrientation.Horizontal,
Spacing = 15,
Children =
{
new BoxView { Color = Color.Blue },
new Label { Text = "Blue", FontSize = Device.GetNamedSize(NamedSize.Large, typeof(Label)), VerticalOptions = LayoutOptions.Center }
}
}
},
// ...
}
};
}
}
Descarga del ejemplo
orientada verticalmente a
a StackLayout