[英]How do I drag and move an image around inside a Grid in WPF?
如何在網格內部拖動和移動圖像?
幾天來一直在嘗試解決我的問題,沒有結果..這是我的xaml代碼。
<Canvas>
<Grid Canvas.Left="134" Canvas.Top="98" Height="500" Width="1010">
<ContentControl x:Name="poolContainer">
</ContentControl>
<Grid DragEnter="Grid_DragEnter" AllowDrop="True">
<Image Canvas.Left="902" Canvas.Top="324" Height="42" Name="CueStick" Visibility="Visible" Source="/NYP_FYPJ_VP2014;component/Images/cue.png" Margin="780,230,-92,228" Drop="CueStick_DragDrop" MouseMove="CueStick_MouseMove" MouseDown="CueStick_MouseDown" MouseUp="CueStick_MouseUp"></Image>
</Grid>
</Grid>
<RepeatButton Canvas.Left="1175" Canvas.Top="397" Content="Rotate" Height="23" Name="buttonUp" Width="74" Click="buttonUp_Click" />
</Canvas>
這是我的圖像拖動的xaml.cs代碼
bool drag = false;
int x = 0;
int y = 0;
private bool isPictureReadyToDrag;
private void SetPosition()
{
CueStick.Location = new Point(MousePosition.X - this.Left - CueStick.Width / 2,
MousePosition.Y - this.Top - CueStick.Height);
}
private void CueStick_MouseMove(object sender, MouseEventArgs e)
{
if (isPictureReadyToDrag)
SetPosition();
}
private void CueStick_MouseDown(object sender, MouseButtonEventArgs e)
{
isPictureReadyToDrag = true;
SetPosition();
}
private void CueStick_MouseUp(object sender, MouseButtonEventArgs e)
{
isPictureReadyToDrag = false;
}
您在幾個地方做錯了。
圖像放置在Grid
,其位置僅由Margin
屬性Canvas.Top/Left
控制,您可以將其刪除。
<Image Canvas.Left="202" Canvas.Top="324" Margin="780,230,-92,228"
然后在后面的代碼中,設置圖片的Margin
屬性,而不是Location
(沒有此類屬性)。
CueStick.Margin = new Thickness(...
灣 為圖像設置顯式寬度,因為您在后面的代碼中使用了該值。
<Image Width="229" Height="42"
C。 您沒有正確使用鼠標位置。 你可以從MouseEventArgs
/ MouseButtonEventArgs
獲得它,類似
private void CueStick_MouseDown(object sender, MouseButtonEventArgs e)
{
isPictureReadyToDrag = true;
double x = e.GetPosition(grid1).X;
double y = e.GetPosition(grid1).Y;
SetPosition(x, y);
}
private void SetPosition(double x, double y)
{
CueStick.Margin = new Thickness(x - CueStick.Width / 2,
y - CueStick.Height / 2, 0, 0);
}
注意grid1
是圖像的包含Grid。
<Grid x:Name="grid1" DragEnter="Grid_DragEnter" AllowDrop="True">
<Image...
調試以獲取正確的Margin
的艱苦工作留給了您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.