如何在WPF中的网格内拖动和移动图像?

时间:2014-11-10 00:44:37

标签: c# wpf drag grid-layout

如何在网格内拖动和移动图像?

一直试图解决我的问题好几天,没有结果..这是我的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;
}

1 个答案:

答案 0 :(得分:1)

你在几个地方做错了。

图片放在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"

℃。您没有正确使用鼠标位置;你可以从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 x:Name="grid1" DragEnter="Grid_DragEnter" AllowDrop="True">
    <Image...

为了获得正确的Margin,需要进行调试的艰苦工作。