这是 WPF 中 Draggable Rectangle 的实际工作示例,这正是 Rachel 上面所说的。
你可以在标签里面放任何UserControl
// etc StackPanel
。Grid
Canvas
我这样做是因为我在拖动 a 时遇到了问题StackPanel
,问题实际上是我在面板上设置了一个边距,所以它被抵消了。
当您拖动它时,它不会跳过。
<Window x:Class="WpfApp1.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:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Canvas x:Name="canvas" Background="Transparent" PreviewMouseLeftButtonDown="PreviewDown" PreviewMouseLeftButtonUp="PreviewUp" MouseMove="MoveMouse">
<Rectangle x:Name="Rectangle" HorizontalAlignment="Left" Fill="Black" Height="85" Margin="0" Stroke="Black" VerticalAlignment="Top" Width="82" />
</Canvas>
</Grid>
</Window>
XAML
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 WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private object movingObject;
private double firstXPos, firstYPos;
private void PreviewDown(object sender, MouseButtonEventArgs e)
{
firstXPos = e.GetPosition(Rectangle).X;
firstYPos = e.GetPosition(Rectangle).Y;
movingObject = sender;
}
private void PreviewUp(object sender, MouseButtonEventArgs e)
{
movingObject = null;
}
private void MoveMouse(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed && sender == movingObject)
{
double newLeft = e.GetPosition(canvas).X - firstXPos - canvas.Margin.Left;
Rectangle.SetValue(Canvas.LeftProperty, newLeft);
double newTop = e.GetPosition(canvas).Y - firstYPos - canvas.Margin.Top;
Rectangle.SetValue(Canvas.TopProperty, newTop);
}
}
}
}
MainWindow.cs