C# WPF-如何绑定控件';s位置到当前鼠标位置?
有没有办法绑定到XAML文件中WPF中的鼠标位置?还是必须用代码来完成?我在画布中有一个控件,我只希望当鼠标光标在画布中时控件跟随鼠标 谢谢C# WPF-如何绑定控件';s位置到当前鼠标位置?,c#,wpf,xaml,data-binding,mouse-position,C#,Wpf,Xaml,Data Binding,Mouse Position,有没有办法绑定到XAML文件中WPF中的鼠标位置?还是必须用代码来完成?我在画布中有一个控件,我只希望当鼠标光标在画布中时控件跟随鼠标 谢谢 编辑: 好的,我用代码隐藏文件找到了一种相对简单的方法。我在画布上添加了MouseMove事件处理程序,然后添加: private void Canvas_MouseMove(object sender, MouseEventArgs e) { // Get the x and y coordinates of the m
编辑: 好的,我用代码隐藏文件找到了一种相对简单的方法。我在画布上添加了MouseMove事件处理程序,然后添加:
private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
// Get the x and y coordinates of the mouse pointer.
System.Windows.Point position = e.GetPosition(this);
double pX = position.X;
double pY = position.Y;
// Sets the position of the image to the mouse coordinates.
myMouseImage.SetValue(Canvas.LeftProperty, pX);
myMouseImage.SetValue(Canvas.TopProperty, pY);
}
用作指南。我试着为此制作一种装饰器。 将对象、要控制的鼠标位置和一些控件绑定到decorator MousePosition属性
public class MouseTrackerDecorator : Decorator
{
static readonly DependencyProperty MousePositionProperty;
static MouseTrackerDecorator()
{
MousePositionProperty = DependencyProperty.Register("MousePosition", typeof(Point), typeof(MouseTrackerDecorator));
}
public override UIElement Child
{
get
{
return base.Child;
}
set
{
if (base.Child != null)
base.Child.MouseMove -= _controlledObject_MouseMove;
base.Child = value;
base.Child.MouseMove += _controlledObject_MouseMove;
}
}
public Point MousePosition
{
get
{
return (Point)GetValue(MouseTrackerDecorator.MousePositionProperty);
}
set
{
SetValue(MouseTrackerDecorator.MousePositionProperty, value);
}
}
void _controlledObject_MouseMove(object sender, MouseEventArgs e)
{
Point p = e.GetPosition(base.Child);
// Here you can add some validation logic
MousePosition = p;
}
}
和XAML
<local:MouseTrackerDecorator x:Name="mouseTracker">
<Canvas Width="200" Height="200" Background="Red">
<Button Width="20" Height="20" Canvas.Left="{Binding ElementName=mouseTracker, Path=MousePosition.X}" Canvas.Top="{Binding ElementName=mouseTracker, Path=MousePosition.Y}" />
</Canvas>
</local:MouseTrackerDecorator>
仅尝试了几个示例。我认为msdn文档的措辞不正确 “如何:使对象跟随鼠标指针” 应该是 “如何:根据鼠标位置增加对象大小” 无论如何 我可以通过更改画布属性来实现这种效果。也不确定为什么每个人都将事件处理程序附加到顶级布局属性下的对象,而不是窗口。也许你和网上的大多数例子都有不同的效果
<Window x:Class="FollowMouse.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" MouseMove="MouseMoveHandler">
<Canvas>
<Ellipse Name="ellipse" Fill="LightBlue"Width="100" Height="100"/>
</Canvas>
谢谢,这不仅对鼠标位置非常有用,而且对使用装饰器“提取”其他属性也非常有用。
private void MouseMoveHandler(object sender, MouseEventArgs e)
{
/// Get the x and y coordinates of the mouse pointer.
System.Windows.Point position = e.GetPosition(this);
double pX = position.X;
double pY = position.Y;
/// Sets eclipse to the mouse coordinates.
Canvas.SetLeft(ellipse, pX);
Canvas.SetTop(ellipse, pY);
Canvas.SetRight(ellipse, pX);
}