【发布时间】:2016-07-24 21:16:28
【问题描述】:
过去几天我一直在试图弄清楚如何在 C# 的 WPF 中使用 DragDrop 功能,这样我就可以创建一个按钮并在画布中拖动它。我想我错过了一些东西,但经过努力研究后,我无法弄清楚它是什么。我需要做的就是在画布中拖动按钮。
这是我的 XAML 代码:
x:Class="DragDrop_Test.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
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"
xmlns:local="clr-namespace:DragDrop_Test"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Canvas Name="MyCanvas" Width = "300" Height= "200" Background="WhiteSmoke" Margin= "10, 0,190,100" AllowDrop="True" Drop="Canvas_Drop">
<Button Name="btn" Content="Button1" MouseMove="btn_MouseMove" PreviewMouseLeftButtonDown="btn_PreviewMouseLeftButtonDown">
</Button>
</Canvas>
</Window>
这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace DragDrop_Test
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Control draggedItem;
bool IsDragging;
public MainWindow()
{
InitializeComponent();
IsDragging = false;
}
private void Canvas_Drop(object sender, DragEventArgs e)
{
if (!IsDragging)
return;
IsDragging = false;
}
private void btn_MouseMove(object sender, MouseEventArgs e)
{
var dependencyObject = (Button)sender;
draggedItem = dependencyObject;
if (!IsDragging)
return;
if (dependencyObject != null && dependencyObject.IsMouseOver)
{
DragDrop.DoDragDrop(dependencyObject, dependencyObject, DragDropEffects.Move);
}
}
private void btn_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
IsDragging = true;
draggedItem = (Button)sender;
}
}
}
提前致谢
【问题讨论】:
-
另请参阅stackoverflow.com/questions/7810683/moving-buttons-in-a-canvas,了解有关拖动按钮的具体细节。
标签: c# wpf drag-and-drop