Listes¶
Afficher une collection : simple, sélectionnable, arborescente ou tabulaire.
Le principe commun¶
Toutes les listes fonctionnent pareil : une collection (ItemsSource), un modèle par élément (ItemTemplate)
et un panel qui range les éléments (ItemsPanel).
flowchart LR
S["ItemsSource<br/>(collection d'objets)"] --> T["ItemTemplate<br/>(1 objet → 1 visuel)"]
T --> P["ItemsPanel<br/>(StackPanel, WrapPanel…)"]
P --> L["Liste affichée"]
| Contrôle | Sélection | Usage |
|---|---|---|
ItemsControl |
non | afficher simplement |
ListBox |
oui | choisir un ou plusieurs éléments |
TreeView |
oui | hiérarchie (dossiers) |
DataGrid |
oui | tableau en colonnes, tri, édition |
ItemsControl¶
Affiche des éléments, sans sélection.
<ItemsControl ItemsSource="{Binding Etapes}">
<ItemsControl.ItemTemplate>
<DataTemplate x:DataType="x:String">
<TextBlock Text="{Binding}" Margin="0,4" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Changer le panel¶
<ItemsControl ItemsSource="{Binding Tags}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
ListBox¶
Éléments en dur¶
Boîte de réceptionEnvoyésCorbeille
<ListBox SelectedIndex="0">
<ListBoxItem>Boîte de réception</ListBoxItem>
<ListBoxItem>Envoyés</ListBoxItem>
<ListBoxItem>Corbeille</ListBoxItem>
</ListBox>
Depuis une collection¶
ALAda Lovelace
ada@exemple.fr ATAlan Turing
alan@exemple.fr GHGrace Hopper
grace@exemple.fr
ada@exemple.fr ATAlan Turing
alan@exemple.fr GHGrace Hopper
grace@exemple.fr
<ListBox ItemsSource="{Binding Contacts}" SelectedItem="{Binding ContactChoisi}">
<ListBox.ItemTemplate>
<DataTemplate x:DataType="m:Contact">
<Grid ColumnDefinitions="Auto,*" ColumnSpacing="12">
<Border Width="36" Height="36" CornerRadius="18" Background="#C4B5FD">
<TextBlock Text="{Binding Initiales}" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
<StackPanel Grid.Column="1">
<TextBlock Text="{Binding Nom}" FontWeight="SemiBold" />
<TextBlock Text="{Binding Email}" Opacity="0.6" FontSize="12" />
</StackPanel>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Sélection multiple¶
rapport.pdfphoto.jpgbudget.xlsxnotes.txt
<ListBox SelectionMode="Multiple" ItemsSource="{Binding Fichiers}"
SelectedItems="{Binding FichiersChoisis}" />
<!-- Un clic coche/décoche, sans Ctrl -->
<ListBox SelectionMode="Multiple,Toggle" />
Réagir à la sélection¶
private void OnSelection(object? sender, SelectionChangedEventArgs e)
{
foreach (var ajout in e.AddedItems) Debug.WriteLine($"+ {ajout}");
foreach (var retrait in e.RemovedItems) Debug.WriteLine($"- {retrait}");
}
Liste horizontale¶
TousLivresMusiqueFilmsJeux
<ListBox ItemsSource="{Binding Categories}"
ScrollViewer.HorizontalScrollBarVisibility="Auto">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
Styler les éléments¶
<ListBox.Styles>
<Style Selector="ListBoxItem">
<Setter Property="Padding" Value="12,8" />
<Setter Property="CornerRadius" Value="6" />
</Style>
<Style Selector="ListBoxItem:selected /template/ ContentPresenter">
<Setter Property="Background" Value="#EDE9FE" />
</Style>
</ListBox.Styles>
Grandes listes¶
flowchart LR
C["10 000 objets<br/>dans ItemsSource"] --> V["~15 conteneurs créés<br/>(ceux à l'écran)"]
V -- "défilement" --> R["conteneurs recyclés<br/>pour les nouveaux éléments"]
ListBox virtualise par défaut : seuls les éléments visibles sont créés. Gardez-la dans un conteneur
de taille finie (Grid avec *), pas dans un StackPanel ni un ScrollViewer.
Accéder aux conteneurs v12¶
var conteneur = Liste.ContainerFromIndex(3); // remplace ItemContainerGenerator.ContainerFromIndex
var index = Liste.IndexFromContainer(conteneur!);
TreeView¶
📁 Projets
📁 Site web
📄 index.html
📁 Application mobile
📁 Archives
TreeDataTemplate = un DataTemplate qui indique aussi où sont les enfants (ItemsSource="{Binding Enfants}").
<TreeView ItemsSource="{Binding Dossiers}">
<TreeView.ItemTemplate>
<TreeDataTemplate x:DataType="m:Dossier" ItemsSource="{Binding Enfants}">
<StackPanel Orientation="Horizontal" Spacing="6">
<TextBlock Text="📁" />
<TextBlock Text="{Binding Nom}" />
</StackPanel>
</TreeDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
public class Dossier
{
public string Nom { get; set; } = "";
public ObservableCollection<Dossier> Enfants { get; } = new();
}
En dur¶
<TreeView>
<TreeViewItem Header="Projets" IsExpanded="True">
<TreeViewItem Header="Site web" />
<TreeViewItem Header="Application mobile" />
</TreeViewItem>
<TreeViewItem Header="Archives" />
</TreeView>
DataGrid¶
Paquet séparé :
App.axaml
<Application.Styles>
<FluentTheme />
<StyleInclude Source="avares://Avalonia.Controls.DataGrid/Themes/Fluent.xaml" />
</Application.Styles>
| N° ▲ | Client | Montant | Payée | Statut |
|---|---|---|---|---|
| 1001 | Ada L. | 120,00 € | Payée | |
| 1002 | Alan T. | 45,50 € | En attente | |
| 1003 | Grace H. | 310,00 € | Payée |
<DataGrid ItemsSource="{Binding Commandes}"
AutoGenerateColumns="False"
IsReadOnly="False"
CanUserSortColumns="True"
CanUserResizeColumns="True"
GridLinesVisibility="Horizontal">
<DataGrid.Columns>
<DataGridTextColumn Header="N°" Binding="{Binding Numero}" Width="80" IsReadOnly="True" />
<DataGridTextColumn Header="Client" Binding="{Binding Client}" Width="*" />
<DataGridTextColumn Header="Montant" Binding="{Binding Montant, StringFormat='{}{0:C}'}" />
<DataGridCheckBoxColumn Header="Payée" Binding="{Binding EstPayee}" />
<DataGridTemplateColumn Header="Statut">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate x:DataType="m:Commande">
<Border Background="#EDE9FE" CornerRadius="8" Padding="6,2" Margin="4"
HorizontalAlignment="Left">
<TextBlock Text="{Binding Statut}" FontSize="12" />
</Border>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Tip
Pour des données hiérarchiques en colonnes, regardez TreeDataGrid (paquet Avalonia.Controls.TreeDataGrid).
Liste vide¶
Aucune tâche 🎉
<Panel>
<ListBox x:Name="Liste" ItemsSource="{Binding Taches}" />
<TextBlock Text="Aucune tâche 🎉" Opacity="0.6"
HorizontalAlignment="Center" VerticalAlignment="Center"
IsVisible="{Binding !Taches.Count}" />
</Panel>
! inverse la valeur : Count == 0 donne true.