2014-07-09 40 views
0

我仍然在學習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> 

而這是我的事件處理程序。我可能在那裏有一些不相關的代碼,但是一旦我開始工作,我就可以清理它。

​​

的問題是,當我在圖像上單擊,就會消失......

//注意我只是拿出InvalidateVisual,它仍然無法正常工作,但圖像跳下屏幕現在。

// note2我添加了一些代碼來最大化窗口,並幫助。我瞭解到圖像正在遠離我的鼠標。看起來mousemove事件只在鼠標位於圖像上方時纔會觸發,並在圖像關閉後立即停止,因此它有點像從鼠標上跑開......

+0

你吃過看看http://stackoverflow.com/questions/5659237/make-object-follow-mouse-on-mousedown-and-stick-on-mouseup – Jamleck

+0

你需要做的第一件事就是使用wpf來獲取你的鼠標座標,並取消winforms導入,座標系統是不同的。第二件事我會做的是使用畫布而不是網格,這樣你可以使用xy座標直接設置你的位置,而不必擔心使用邊距。 –

+0

我試着將它改爲畫布。 – user3796261

回答

0

試試這個。使用Mouse.GetPosition(this)獲得相對鼠標指針到WindowWindow爲原點的左上角的位置..

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; } 
} 
+0

這正是我想要的。感謝上帝,因爲我不知道在給出的其他答案中發生了什麼。 – user3796261