我还在学习WPF,但我想要做的就是在单击图像时按照鼠标左右进行操作。到目前为止,我已经正确地发射了事件,但我认为我没有正确地重新定位图像。
<Image x:Name="LetterBlock" HorizontalAlignment="Left" Height="100" VerticalAlignment="Top" Width="100" MouseDown="ImageOnMouseDown" MouseMove="ImageOnMouseMove">
<Image.Source>
<ImageSource>pack://application:,,,/Resources/A_LetterBlock.jpg</ImageSource>
</Image.Source>
<Image.Margin >
<Thickness>145,104,0,0</Thickness>
</Image.Margin>
</Image>
这是我的事件处理程序。我可能在那里有一些不相关的代码,但是一旦我开始工作,我就可以清理它。
public void ImageOnMouseDown(Object sender, MouseEventArgs e) {
IsClicked = true;
}
public void ImageOnMouseMove(Object sender, MouseEventArgs e)
{
if (!IsClicked)
return;
Point position = GetMousePositionWindowsForms();
Thickness nMargin = new Thickness(position.X, position.Y, 0, 0);
LetterBlock.Margin = nMargin;
}
private Point GetMousePositionWindowsForms()
{
System.Drawing.Point point = System.Windows.Forms.Control.MousePosition;
return new Point(point.X, point.Y);
}
问题是,当我点击图像时,它会消失......
//注意我刚拿出InvalidateVisual但它仍然不起作用,但图像现在跳出屏幕。
// note2我添加了一些代码来最大化窗口,这有帮助。我了解到图像正在远离我的鼠标。看起来mousemove事件只在鼠标位于图像顶部时触发,并在图像离开后立即停止,因此它有点像它正在远离鼠标...
答案 0 :(得分:0)
试试这个。使用Mouse.GetPosition(this)
获取鼠标指针相对于Window
的位置,Window
的左上角是原点..
using System;
using System.Windows;
using System.Windows.Input;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void LetterBlock_MouseDown(object sender, MouseButtonEventArgs e)
{
IsClicked = !IsClicked;
if (IsClicked)
{
LetterBlock.CaptureMouse();
}
else
{
LetterBlock.ReleaseMouseCapture();
}
}
private void LetterBlock_MouseMove(object sender, MouseEventArgs e)
{
if (!IsClicked)
return;
Point position = Mouse.GetPosition(this);
Thickness nMargin = new Thickness(position.X, position.Y, 0, 0);
LetterBlock.Margin = nMargin;
//InvalidateVisual();
}
public bool IsClicked { get; set; }
}