「東雲 忠太郎」の平凡な日常のできごと

「東雲 忠太郎」の平凡な日常のできごと

2024.03.18
XML
カテゴリ: C#.NET


以下は、C# WPF アプリケーションで、ドラッグアンドドロップによってパネル間でボタンを移動できるようにするサンプルコードです。この例では、Canvas コントロールを使用してボタンを配置し、ボタンをドラッグして他のパネルにドロップできるようにします。


```csharp

using System.Windows;

using System.Windows.Controls;

using System.Windows.Input;

using System.Windows.Media;


namespace DragAndDropExample

{

    public partial class MainWindow : Window

    {

        private bool isDragging = false;

        private Button draggedButton = null;


        public MainWindow()

        {

            InitializeComponent();

        }


        private void Button_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)

        {

            // ボタンがクリックされたときの処理

            isDragging = true;

            draggedButton = sender as Button;

            draggedButton.CaptureMouse();

        }


        private void Button_MouseMove(object sender, MouseEventArgs e)

        {

            // ボタンがドラッグされているときの処理

            if (isDragging && draggedButton != null)

            {

                Point currentPosition = e.GetPosition(canvas);


                Canvas.SetLeft(draggedButton, currentPosition.X - draggedButton.ActualWidth / 2);

                Canvas.SetTop(draggedButton, currentPosition.Y - draggedButton.ActualHeight / 2);

            }

        }


        private void Button_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)

        {

            // ボタンがドロップされたときの処理

            if (isDragging && draggedButton != null)

            {

                isDragging = false;

                draggedButton.ReleaseMouseCapture();

                draggedButton = null;

            }

        }

    }

}

```


```xml

<Window x:Class="DragAndDropExample.MainWindow"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="Drag and Drop Example" Height="300" Width="300">

    <Grid>

        <Canvas x:Name="canvas" Background="LightGray" AllowDrop="True"

                MouseMove="Button_MouseMove" MouseLeftButtonUp="Button_MouseLeftButtonUp">


            <!-- ドラッグ可能なボタン -->

            <Button x:Name="button" Content="Drag me" Width="100" Height="30"

                    MouseLeftButtonDown="Button_MouseLeftButtonDown"/>

        </Canvas>

    </Grid>

</Window>

```


このコードでは、Canvas コントロール内に配置されたボタンがドラッグ可能になります。ボタンがマウスの左ボタンでクリックされると、マウスの移動に応じてボタンがドラッグされます。マウスの左ボタンが離されると、ボタンがドロップされ、その位置に固定されます。






お気に入りの記事を「いいね!」で応援しよう

Last updated  2024.03.18 08:32:38


【毎日開催】
15記事にいいね!で1ポイント
10秒滞在
いいね! -- / --
おめでとうございます!
ミッションを達成しました。
※「ポイントを獲得する」ボタンを押すと広告が表示されます。
x

© Rakuten Group, Inc.
Create a Mobile Website
スマートフォン版を閲覧 | PC版を閲覧
Share by: