Xamarin.Forms TableViewXamarin.Forms TableView
Descargar el ejemplo
Download the sample
TableView
es una vista para mostrar listas desplazables de datos u opciones en las que hay filas que no comparten la misma plantilla.TableView
is a view for displaying scrollable lists of data or choices where there are rows that don't share the same template. A diferencia de ListView, no TableView
tiene el concepto de ItemsSource
, por lo que los elementos se deben agregar manualmente como elementos secundarios.Unlike ListView, TableView
does not have the concept of an ItemsSource
, so items must be manually added as children.
Casos de usoUse cases
TableView
resulta útil cuando:TableView
is useful when:
- presentar una lista de opciones de configuraciónpresenting a list of settings,
- recopilación de datos en un formulario ocollecting data in a form, or
- Mostrar los datos que se presentan de manera diferente de fila a fila (por ejemplo, números, porcentajes e imágenes).showing data that is presented differently from row to row (e.g. numbers, percentages and images).
TableView
controla el desplazamiento y la colocación de las filas en secciones atractivas, una necesidad común de los escenarios anteriores.TableView
handles scrolling and laying out rows in attractive sections, a common need for the above scenarios. El TableView
control usa la vista equivalente subyacente de cada plataforma cuando está disponible, lo que crea una apariencia nativa para cada plataforma.The TableView
control uses each platform's underlying equivalent view when available, creating a native look for each platform.
EstructuraStructure
Los elementos de TableView
se organizan en secciones.Elements in a TableView
are organized into sections. En la raíz de TableView
TableRoot
, es, que es el elemento primario de una o más instancias de TableSection
.At the root of the TableView
is the TableRoot
, which is parent to one or more TableSection
instances. Cada TableSection
una consta de un encabezado y una o varias ViewCell
instancias:Each TableSection
consists of a heading and one or more ViewCell
instances:
<TableView Intent="Settings">
<TableRoot>
<TableSection Title="Ring">
<SwitchCell Text="New Voice Mail" />
<SwitchCell Text="New Mail" On="true" />
</TableSection>
</TableRoot>
</TableView>
El código de C# equivalente es el siguiente:The equivalent C# code is:
Content = new TableView
{
Root = new TableRoot
{
new TableSection("Ring")
{
// TableSection constructor takes title as an optional parameter
new SwitchCell { Text = "New Voice Mail" },
new SwitchCell { Text = "New Mail", On = true }
}
},
Intent = TableIntent.Settings
};
AspectoAppearance
TableView
expone la Intent
propiedad, que se puede establecer en cualquiera de los TableIntent
miembros de enumeración:TableView
exposes the Intent
property, which can be set to any of the TableIntent
enumeration members:
Data
: sirve para mostrar entradas de datos.Data
– for use when displaying data entries. Tenga en cuenta que ListView puede ser una opción mejor para desplazar listas de datos.Note that ListView may be a better option for scrolling lists of data.Form
: se utiliza cuando el TableView actúa como un formulario.Form
– for use when the TableView is acting as a Form.Menu
: se usa para presentar un menú de selecciones.Menu
– for use when presenting a menu of selections.Settings
: se usa para mostrar una lista de opciones de configuración.Settings
– for use when displaying a list of configuration settings.
El TableIntent
valor que elija puede afectar al modo TableView
en que aparece en cada plataforma.The TableIntent
value you choose may impact how the TableView
appears on each platform. Incluso si no hay diferencias claras, se recomienda seleccionar el TableIntent
que más se aproxime a la forma de usar la tabla.Even if there are not clear differences, it is a best practice to select the TableIntent
that most closely matches how you intend to use the table.
Además, el color del texto que se muestra para cada TableSection
puede cambiarse estableciendo la TextColor
propiedad en Color
.In addition, the color of the text displayed for each TableSection
can be changed by setting the TextColor
property to a Color
.
Celdas integradasBuilt-in cells
Xamarin.Forms incluye las celdas integradas para recopilar y Mostrar información.Xamarin.Forms comes with built-in cells for collecting and displaying information. Aunque ListView
y TableView
pueden utilizar las mismas celdas, SwitchCell
y EntryCell
son las más relevantes para un TableView
escenario.Although ListView
and TableView
can use all of the same cells, SwitchCell
and EntryCell
are the most relevant for a TableView
scenario.
Vea la apariencia de una celda de ListView para obtener una descripción detallada de TextCell y ImageCell.See ListView Cell Appearance for a detailed description of TextCell and ImageCell.
SwitchCellSwitchCell
SwitchCell
es el control que se va a utilizar para presentar y capturar un estado ON/OFF o true
/ false
.SwitchCell
is the control to use for presenting and capturing an on/off or true
/false
state. Define las siguientes propiedades:It defines the following properties:
Text
: texto que se va a mostrar junto al modificador.Text
– text to display beside the switch.On
: indica si el modificador se muestra como activado o desactivado.On
– whether the switch is displayed as on or off.OnColor
: elColor
del modificador cuando se encuentra en la posición de encendido.OnColor
– theColor
of the switch when it's in the on position.
Todas estas propiedades son enlazables.All of these properties are bindable.
SwitchCell
también expone el OnChanged
evento, lo que le permite responder a los cambios en el estado de la celda.SwitchCell
also exposes the OnChanged
event, allowing you to respond to changes in the cell's state.
EntryCellEntryCell
EntryCell
resulta útil cuando es necesario Mostrar datos de texto que el usuario puede editar.EntryCell
is useful when you need to display text data that the user can edit. Define las siguientes propiedades:It defines the following properties:
Keyboard
: Teclado que se va a mostrar durante la edición.Keyboard
– The keyboard to display while editing. Hay opciones para elementos como valores numéricos, correo electrónico, números de teléfono, etc. consulte los documentos de la API.There are options for things like numeric values, email, phone numbers, etc. See the API docs.Label
: El texto de la etiqueta que se va a mostrar a la izquierda del campo de entrada de texto.Label
– The label text to display to the left of the text entry field.LabelColor
: El color del texto de la etiqueta.LabelColor
– The color of the label text.Placeholder
: Texto que se va a mostrar en el campo de entrada cuando es null o está vacío.Placeholder
– Text to display in the entry field when it is null or empty. Este texto desaparece cuando comienza la entrada de texto.This text disappears when text entry begins.Text
: El texto del campo de entrada.Text
– The text in the entry field.HorizontalTextAlignment
: Alineación horizontal del texto.HorizontalTextAlignment
– The horizontal alignment of the text. Los valores son Center, Left o Right aligned.Values are center, left, or right aligned. Vea los documentos de la API.See the API docs.VerticalTextAlignment
: Alineación vertical del texto.VerticalTextAlignment
– The vertical alignment of the text. Los valores sonStart
,Center
oEnd
.Values areStart
,Center
, orEnd
.
EntryCell
también expone el Completed
evento, que se desencadena cuando el usuario presiona el botón ' DONE ' en el teclado mientras edita el texto.EntryCell
also exposes the Completed
event, which is fired when the user hits the 'done' button on the keyboard while editing text.
Celdas personalizadasCustom cells
Cuando las celdas integradas no son suficientes, se pueden usar celdas personalizadas para presentar y capturar datos de la forma que tenga sentido para la aplicación.When the built-in cells aren't enough, custom cells can be used to present and capture data in the way that makes sense for your app. Por ejemplo, puede que desee presentar un control deslizante para permitir que un usuario elija la opacidad de una imagen.For example, you may want to present a slider to allow a user to choose the opacity of an image.
Todas las celdas personalizadas se deben derivar de ViewCell
, la misma clase base que usan todos los tipos de celdas integrados.All custom cells must derive from ViewCell
, the same base class that all of the built-in cell types use.
Este es un ejemplo de una celda personalizada:This is an example of a custom cell:
En el ejemplo siguiente se muestra el código XAML que se usa para crear TableView
en las capturas de pantallas anteriores:The following example shows the XAML used to create the TableView
in the screenshots above:
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="DemoTableView.TablePage"
Title="TableView">
<TableView Intent="Settings">
<TableRoot>
<TableSection Title="Getting Started">
<ViewCell>
<StackLayout Orientation="Horizontal">
<Image Source="bulb.png" />
<Label Text="left"
TextColor="#f35e20" />
<Label Text="right"
HorizontalOptions="EndAndExpand"
TextColor="#503026" />
</StackLayout>
</ViewCell>
</TableSection>
</TableRoot>
</TableView>
</ContentPage>
El código de C# equivalente es el siguiente:The equivalent C# code is:
var table = new TableView();
table.Intent = TableIntent.Settings;
var layout = new StackLayout() { Orientation = StackOrientation.Horizontal };
layout.Children.Add (new Image() { Source = "bulb.png"});
layout.Children.Add (new Label()
{
Text = "left",
TextColor = Color.FromHex("#f35e20"),
VerticalOptions = LayoutOptions.Center
});
layout.Children.Add (new Label ()
{
Text = "right",
TextColor = Color.FromHex ("#503026"),
VerticalOptions = LayoutOptions.Center,
HorizontalOptions = LayoutOptions.EndAndExpand
});
table.Root = new TableRoot ()
{
new TableSection("Getting Started")
{
new ViewCell() {View = layout}
}
};
Content = table;
El elemento raíz en TableView
es TableRoot
y hay TableSection
inmediatamente debajo de TableRoot
.The root element under the TableView
is the TableRoot
, and there is a TableSection
immediately underneath the TableRoot
. ViewCell
Se define directamente en TableSection
, y StackLayout
se usa para administrar el diseño de la celda personalizada, aunque aquí se podría usar cualquier diseño.The ViewCell
is defined directly under the TableSection
, and a StackLayout
is used to manage the layout of the custom cell, although any layout could be used here.
Nota
A diferencia de ListView
, no TableView
requiere que las celdas personalizadas (o ninguna) estén definidas en ItemTemplate
.Unlike ListView
, TableView
does not require that custom (or any) cells are defined in an ItemTemplate
.
Alto de filaRow height
La TableView
clase tiene dos propiedades que se pueden usar para cambiar el alto de las filas de las celdas:The TableView
class has two properties that can be used to change the row height of cells:
RowHeight
: establece el alto de cada fila en unint
.RowHeight
– sets the height of each row to anint
.HasUnevenRows
: las filas tienen altos variables si están establecidas entrue
.HasUnevenRows
– rows have varying heights if set totrue
. Tenga en cuenta que al establecer esta propiedad en, el alto de lastrue
filas se calculará y aplicará automáticamente Xamarin.Forms .Note that when setting this property totrue
, row heights will automatically be calculated and applied by Xamarin.Forms.
Cuando cambia el alto del contenido de una celda de un TableView
, el alto de las filas se actualiza implícitamente en Android y en el plataforma universal de Windows (UWP).When the height of content in a cell in a TableView
is changed, the row height is implicitly updated on Android and the Universal Windows Platform (UWP). Sin embargo, en iOS se debe forzar la actualización estableciendo la HasUnevenRows
propiedad en true
y llamando al Cell.ForceUpdateSize
método.However, on iOS it must be forced to update by setting the HasUnevenRows
property to true
and by calling the Cell.ForceUpdateSize
method.
En el ejemplo de XAML siguiente se muestra un TableView
que contiene un ViewCell
:The following XAML example shows a TableView
that contains a ViewCell
:
<ContentPage ...>
<TableView ...
HasUnevenRows="true">
<TableRoot>
...
<TableSection ...>
...
<ViewCell x:Name="_viewCell"
Tapped="OnViewCellTapped">
<Grid Margin="15,0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label Text="Tap this cell." />
<Label x:Name="_target"
Grid.Row="1"
Text="The cell has changed size."
IsVisible="false" />
</Grid>
</ViewCell>
</TableSection>
</TableRoot>
</TableView>
</ContentPage>
Cuando ViewCell
se puntea en, OnViewCellTapped
se ejecuta el controlador de eventos:When the ViewCell
is tapped, the OnViewCellTapped
event handler is executed:
void OnViewCellTapped(object sender, EventArgs e)
{
_target.IsVisible = !_target.IsVisible;
_viewCell.ForceUpdateSize();
}
El OnViewCellTapped
controlador de eventos muestra u oculta el segundo Label
en y ViewCell
actualiza explícitamente el tamaño de la celda llamando al Cell.ForceUpdateSize
método.The OnViewCellTapped
event handler shows or hides the second Label
in the ViewCell
, and explicitly updates the cell's size by calling the Cell.ForceUpdateSize
method.
Las capturas de pantallas siguientes muestran la celda antes de que se Puntee sobre:The following screenshots show the cell prior to being tapped upon:
Las siguientes capturas de pantallas muestran la celda después de la derivación:The following screenshots show the cell after being tapped upon:
Importante
Si esta característica está sobreutilizada, existe una gran probabilidad de degradación del rendimiento.There is a strong possibility of performance degradation if this feature is overused.