XAML
<Window x:Class="MoveElement.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:MoveElement"
mc:Ignorable="d"
Title="MainWindow" Height="600" Width="800">
<Grid>
<Canvas x:Name="canvas" Background="LemonChiffon" Width="400" Height="400" MouseMove="canvas_MouseMove" MouseDown="canvas_MouseDown" MouseUp="canvas_MouseUp">
<Ellipse Name="ellipse" Fill="Black" Width="100" Height="100" Margin="-50" RenderTransformOrigin="0.5,0.5">
<Ellipse.RenderTransform>
<TransformGroup>
<TranslateTransform x:Name="transer"/>
</TransformGroup>
</Ellipse.RenderTransform>
</Ellipse>
</Canvas>
</Grid>
</Window>
C#
using System.Diagnostics;
using System.Text;
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 MoveElement
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Rect rect;
public MainWindow()
{
InitializeComponent();
// 移动范围在canvas内
rect = new(0,0,canvas.Width,canvas.Height);
}
private void canvas_MouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
Point P = e.GetPosition(canvas);
double x = P.X;
double y = P.Y;
if(rect.Contains(P)==false)
{
// 如鼠标移出范围,确定移动边界。
if(P.X < 0) x = 0;
if(P.X > rect.Width) x = rect.Width;
if (P.Y < 0) y = 0;
if (P.Y > rect.Height) y = rect.Height;
}
transer.X = x;
transer.Y = y;
}
}
private void canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
// 点击时,移动到鼠标点
Point P = e.GetPosition(canvas);
transer.X = P.X;
transer.Y = P.Y;
// 使鼠标绑定在canvas上,避免移出后不响应移动事件
canvas.CaptureMouse();
}
private void canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
// 解除鼠标绑定
canvas.ReleaseMouseCapture();
}
}
}
关键是要把鼠标捕获在事件发出的控件上,避免移出范围后不再响应。
本文详细介绍了如何使用XAML和C#在Windows应用程序中实现Canvas上的椭圆元素跟随鼠标移动,同时确保鼠标在Canvas范围内并处理边界条件。
1646





