有没有办法在XAML文件中绑定到WPF中的鼠标位置?或者这必须在代码中完成吗?我在Canvas中有一个控件,我只想让控件在鼠标光标位于Canvas中时跟随鼠标。
由于
编辑:
好的,我认为使用代码隐藏文件相对简单。我在Canvas上添加了一个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);
}
使用http://msdn.microsoft.com/en-us/library/ms746626.aspx作为指导。
答案 0 :(得分:8)
我试图为此目的制作一种装饰器。 您将对象,鼠标位置包裹在您想要控制的位置上,并将某些控件绑定到装饰器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>
答案 1 :(得分:0)
仅尝试了几个例子。我认为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);
}