2011-01-26 51 views
0

我正在使用WPF 4和VB.net 2010.我的項目由全屏幕窗口和中心的640x480網格組成。如何在WPF中平滑拖動圖像框?

在這個項目中,我想要有各種各樣的圖像框(其中將具有項目.png圖像),用戶可以拖動並放置在網格上的各個位置。

從本質上講,我需要能夠使項目在網格中被點擊和拖動,並且圖像框仍然可見並且與用戶移動相同的大小。它永遠不能離開電網。我還需要能夠確定對象是否在另一個對象上,因此當釋放鼠標按鈕時,拖動的對象將被「拖放」,並觸發特定的代碼塊。

我該怎麼做?

回答

0

類似的東西到你的「項目」,但用C#

http://pastie.org/1498237

// XAML 

<Window x:Class="MyProject.Window1" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
Title="Window1" Height="500" Width="500"> 
    <Grid> 
     <Canvas x:Name="mycanv"> 
      <Image Width="150" x:Name="myimg" Source="some_source.png"/> 
     </Canvas> 
    </Grid> 
</Window> 

//C# 

private Point mouseClick; 
private double canvasLeft; 
private double canvasTop; 
public Window1() 
{ 
    InitializeComponent(); 
    foreach (object obj in mycanv.Children) 
    { 
     try 
     { 
      Image img = (Image)obj; 
      img.PreviewMouseDown += new MouseButtonEventHandler(myimg_MouseDown); 
      img.PreviewMouseMove += new MouseEventHandler(myimg_MouseMove); 
      img.PreviewMouseUp += new MouseButtonEventHandler(myimg_MouseUp); 
      img.TextInput += new TextCompositionEventHandler(myimg_TextInput); 
      img.LostMouseCapture += new MouseEventHandler(myimg_LostMouseCapture); 
      img.SetValue(Canvas.LeftProperty, 0.0); 
      img.SetValue(Canvas.TopProperty, 0.0); 
     } 
     catch 
     { 
      //do something 
     } 
    } 
} 

void myimg_LostMouseCapture(object sender, MouseEventArgs e) 
{ 
    ((Image)sender).ReleaseMouseCapture(); 
} 

void myimg_TextInput(object sender, TextCompositionEventArgs e) 
{ 
    ((Image)sender).ReleaseMouseCapture(); 
} 

void myimg_MouseUp(object sender, MouseButtonEventArgs e) 
{ 
    ((Image)sender).ReleaseMouseCapture(); 
} 

void myimg_MouseMove(object sender, MouseEventArgs e) 
{ 
    if (((Image)sender).IsMouseCaptured) 
    { 
     Point mouseCurrent = e.GetPosition(null); 
     double Left = mouseCurrent.X - canvasLeft; 
     double Top = mouseCurrent.Y - canvasTop; 
     ((Image)sender).SetValue(Canvas.LeftProperty, canvasLeft + Left); 
     ((Image)sender).SetValue(Canvas.TopProperty, canvasTop + Top); 
     canvasLeft = Canvas.GetLeft(((Image)sender)); 
     canvasTop = Canvas.GetTop(((Image)sender)); 
    } 
} 

void myimg_MouseDown(object sender, MouseButtonEventArgs e) 
{ 
    mouseClick = e.GetPosition(null); 
    canvasLeft = Canvas.GetLeft(((Image)sender)); 
    canvasTop = Canvas.GetTop(((Image)sender)); 
    ((Image)sender).CaptureMouse(); 
} 
+0

當我試圖在其他項目中類似的代碼,有鼠標位置和目標位置之間的差異,因爲對象在640x480網格中,分辨率通常較大。我應該如何解決這個問題? – CodeMouse92 2011-01-26 04:57:03