根据WP8 App中的方向按钮移动对象

时间:2015-01-25 20:09:14

标签: c# xaml windows-phone-8

我试图根据方向按钮向上,向左,向右,向下移动对象。

我将margin属性设置为: -

    img.Margin = new Thickness(l, t, r, b); //L T R B

根据所需的移动量递增/递减值。

我可以通过click事件移动对象。 但是,每当按下按钮并为用户按住时,我都希望将对象移动到所需的方向。一旦用户释放按钮,移动也应该停止。

我尝试使用hold事件,但操作执行一次然后停止。

在另一次尝试中,我尝试循环我的陈述,但应用程序停滞不前。

请帮助我。谢谢!

修改: -

我处理了ManipulationStarted,ManipulationDelta,ManipulationCompleted事件。

现在,只要我按住按钮,我就能移动物体。 但是,我面临的新问题是我必须不停地在屏幕上移动手指才能执行动作。

向上按钮的代码(在垂直方向上移动对象的按钮)是: -

    public double l = 0.0, t = 0.0, r = 0.0, b = 0.0;
    public void move()
    {
        img.Margin = new Thickness(l, t, r, b); //L T R B
    }

    private void up_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
    {

    }

    private void up_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
    {
        t = t + 1.0;
        move();
    }

    private void up_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
    {

    }

我不确定这种方法是否正确。建议。感谢。

1 个答案:

答案 0 :(得分:0)

您应该使用ManipulationStartedManipulationCompleted个事件。它们适用于此处所述的TapHold手势:https://msdn.microsoft.com/en-us/library/windows/apps/ff426933(v=vs.105).aspx

<强>更新

要正确检测点击的开头和结尾,我建议您使用MouseEnterMouseLeaving个事件。 这是一个示例,显示了我如何向下移动一个物体。 目前这是屏幕中央的一个正方形:

<Grid x:Name="objectToMove" Background="red" Height="100" Width="100">
    <Grid.RenderTransform>
        <TranslateTransform x:Name="verticalTransform" Y="0" />
    </Grid.RenderTransform>
</Grid>

背后的代码:

AutoResetEvent autoEvent = new AutoResetEvent(true);

System.Threading.Timer dt;

private void toggle_MouseEnter(object sender, MouseEventArgs e)
{
    dt = new System.Threading.Timer(new TimerCallback(MoveFunct), autoEvent, 0, 1);
}

private void MoveFunct(Object stateInfo)
{
    Deployment.Current.Dispatcher.BeginInvoke(() => { verticalTransform.Y += 3; });
}

private void toggle_MouseLeave(object sender, MouseEventArgs e)
{
    dt.Dispose();
}

请注意,Timer构造函数的最后一个参数包含刻度之间的间隔。同样在MoveFunct函数内部,我调用Dispatcher方法,否则无法访问UI线程。 在示例中,我使用TranslateTransform,在我看来,这比Margin操作更好,因为它需要更新元素整个可视树。