DragAndDrop.axaml代码

<Window xmlns="https://github.com/avaloniaui"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        Height="257.6" Width="392.8"
        x:Class="AvaloniaUI.DragAndDrop"
        Title="DragAndDrop">
    <Grid RowDefinitions="*,*" ColumnDefinitions="*,*" 
          DragDrop.AllowDrop="True" DragDrop.Drop="lblTarget_Drop" DragDrop.DragEnter="lblTarget_DropEnter">
        <TextBox Padding="10" VerticalAlignment="Center" HorizontalAlignment="Center">Drag to this TextBox</TextBox>
        <Label Grid.Column="1" Padding="20" Background="LightGoldenrodYellow"
                   VerticalAlignment="Center"  HorizontalAlignment="Center"
                   PointerPressed="lblSource_MouseDown">Drag me</Label>
        <Label Grid.Row="1" Grid.ColumnSpan="2" Background="LightGoldenrodYellow"
               VerticalAlignment="Center" HorizontalAlignment="Center" Padding="20">Drag to this Label</Label>
    </Grid>
</Window>

DragAndDrop.axaml.cs代码

using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Markup.Xaml;
using Avalonia.VisualTree;
using System;

namespace AvaloniaUI;

public partial class DragAndDrop : Window
{
    public DragAndDrop()
    {
        InitializeComponent();
    }

    private void lblSource_MouseDown(object? sender, PointerPressedEventArgs e)
    {
        var data = new DataObject();
        data.Set(DataFormats.Text, ((Label?)sender)?.Content!);
        DragDrop.DoDragDrop(e, data, DragDropEffects.Copy);
    }
    private void lblTarget_DropEnter(object? sender, DragEventArgs e)
    {
        if (e.Data.Contains(DataFormats.Text))
        {
            e.DragEffects = DragDropEffects.Copy;
        }
        else
        {
            e.DragEffects = DragDropEffects.None;
        }
    }
    private void lblTarget_Drop(object? sender, DragEventArgs e)
    {
        if (sender is Grid grid)
        {
            var pt = e.GetPosition(grid);
            foreach (var c in grid.Children)
            {
                if (c != e.Source && c.GetTransformedBounds()!.Value.Contains(pt))
                {
                    switch (c)
                    {
                        case Label label when e.Data.Contains(DataFormats.Text):
                            label.Content = e.Data.Get(DataFormats.Text);
                            break;
                        case TextBox textbox when e.Data.Contains(DataFormats.Text):
                            textbox.Text = e.Data.Get(DataFormats.Text)?.ToString();
                            break;
                    }
                }
            }
        }
    }
}

运行效果

 

posted on 2025-07-20 16:53  dalgleish  阅读(49)  评论(0)    收藏  举报