Aller au contenu

Glisser-déposer v12

Recevoir des fichiers depuis l'explorateur, ou glisser des éléments dans l'application.

Le déroulement

sequenceDiagram
  participant S as Source (explorateur, autre contrôle)
  participant Z as Zone (DragDrop.AllowDrop)
  S->>Z: DragEnter : le pointeur entre
  loop pendant le survol
    S->>Z: DragOver : accepter ? (e.DragEffects)
  end
  alt relâché sur la zone
    S->>Z: Drop : lire e.DataTransfer
  else sorti de la zone
    S->>Z: DragLeave
  end

Zone de dépôt de fichiers

Aperçu · déposez un vrai fichier depuis votre ordinateur
Déposez vos fichiers ici
<Border x:Name="Zone" DragDrop.AllowDrop="True"
        Height="160" CornerRadius="12" BorderThickness="2" BorderBrush="#C4B5FD"
        Background="#F5F3FF">
  <TextBlock x:Name="Info" Text="Déposez vos fichiers ici"
             HorizontalAlignment="Center" VerticalAlignment="Center" />
</Border>
public MainWindow()
{
    InitializeComponent();
    DragDrop.AddDragOverHandler(Zone, OnDragOver);
    DragDrop.AddDragLeaveHandler(Zone, OnDragLeave);
    DragDrop.AddDropHandler(Zone, OnDrop);
}

private void OnDragOver(object? sender, DragEventArgs e)
{
    var fichiers = e.DataTransfer.Formats.Contains(DataFormat.File);
    e.DragEffects = fichiers ? DragDropEffects.Copy : DragDropEffects.None;
    Zone.Classes.Set("survol", fichiers);
}

private void OnDragLeave(object? sender, DragEventArgs e) => Zone.Classes.Remove("survol");

private void OnDrop(object? sender, DragEventArgs e)
{
    Zone.Classes.Remove("survol");
    var fichiers = e.DataTransfer.TryGetFiles();
    if (fichiers is null) return;

    Info.Text = string.Join(", ", fichiers.Select(f => f.Name));
}
<Style Selector="Border.survol">
  <Setter Property="Background" Value="#EDE9FE" />
  <Setter Property="BorderBrush" Value="#6D28D9" />
</Style>

En XAML

<Border DragDrop.AllowDrop="True"
        DragDrop.DragOver="OnDragOver"
        DragDrop.Drop="OnDrop" />

Recevoir du texte

private void OnDrop(object? sender, DragEventArgs e)
{
    if (e.DataTransfer.Formats.Contains(DataFormat.Text))
        Saisie.Text = e.DataTransfer.TryGetText();
}

Démarrer un glisser

<Border x:Name="Etiquette" Background="#DDD6FE" Padding="8" CornerRadius="6"
        PointerPressed="OnDebutGlisser">
  <TextBlock Text="Glissez-moi" />
</Border>
private async void OnDebutGlisser(object? sender, PointerPressedEventArgs e)
{
    var data = new DataTransfer();
    data.Add(DataTransferItem.Create(DataFormat.Text, "Contenu glissé"));

    var resultat = await DragDrop.DoDragDropAsync(e, data, DragDropEffects.Copy | DragDropEffects.Move);

    if (resultat == DragDropEffects.Move)
        Etiquette.IsVisible = false;
}

Déplacer entre deux listes

Aperçu · glissez une tâche d'une colonne à l'autre
À faireCoursesSportLire
Fait
public static class Formats
{
    public static readonly DataFormat<string> Tache =
        DataFormat.CreateStringApplicationFormat("monapp-tache");
}
<Grid ColumnDefinitions="*,*" ColumnSpacing="12">
  <ListBox x:Name="AFaire" DragDrop.AllowDrop="True" />
  <ListBox x:Name="Fait" Grid.Column="1" DragDrop.AllowDrop="True" />
</Grid>
public MainWindow()
{
    InitializeComponent();
    AFaire.ItemsSource = _aFaire;
    Fait.ItemsSource = _fait;

    foreach (var liste in new[] { AFaire, Fait })
    {
        liste.AddHandler(PointerPressedEvent, OnPress, RoutingStrategies.Tunnel);
        DragDrop.AddDragOverHandler(liste, (_, e) =>
            e.DragEffects = e.DataTransfer.Formats.Contains(Formats.Tache)
                ? DragDropEffects.Move : DragDropEffects.None);
        DragDrop.AddDropHandler(liste, OnDrop);
    }
}

private readonly ObservableCollection<string> _aFaire = new() { "Courses", "Sport", "Lire" };
private readonly ObservableCollection<string> _fait = new();

private async void OnPress(object? sender, PointerPressedEventArgs e)
{
    if (e.Source is not Control { DataContext: string tache }) return;

    var data = new DataTransfer();
    data.Add(DataTransferItem.Create(Formats.Tache, tache));
    await DragDrop.DoDragDropAsync(e, data, DragDropEffects.Move);
}

private void OnDrop(object? sender, DragEventArgs e)
{
    var tache = e.DataTransfer.TryGetValue(Formats.Tache);
    if (tache is null) return;

    var (source, cible) = sender == AFaire ? (_fait, _aFaire) : (_aFaire, _fait);
    if (source.Remove(tache)) cible.Add(tache);
}

Position du dépôt

private void OnDrop(object? sender, DragEventArgs e)
{
    var point = e.GetPosition(Toile);
    Canvas.SetLeft(nouvelElement, point.X);
    Canvas.SetTop(nouvelElement, point.Y);
}

Correspondance v11 → v12

Avalonia 11 Avalonia 12
DragDrop.DoDragDrop(e, data, effets) DragDrop.DoDragDropAsync(e, data, effets)
e.Data e.DataTransfer
e.Data.Contains(DataFormats.Files) e.DataTransfer.Formats.Contains(DataFormat.File)
e.Data.GetFiles() e.DataTransfer.TryGetFiles()
new DataObject() new DataTransfer() + DataTransferItem