在Windows 8 / WinRT中实现DragStarted DragDelta事件

15

如何在 windows 8 / WinRT 中将 DragStartedDragDelta 事件附加到网格?我已经在 windows phone 上使用 GestureService.GetGestureListener() 方法实现了相同的功能。我尝试在 windows 8 中用 ManipulationStarted 和 ManipulationDelta 事件替换代码,但结果不同。在 windows phone 上,对于单个拖动操作,它会多次进入 DragDelta 事件。但是在 windows 8 中,在类似的拖动操作中,ManupulationDelta 事件只触发一次。


你在网格上设置了 IsManipulationEnabled = true 吗? - Roger Rowland
我没有找到任何关于网格的属性。我将属性ManipulationMode设置为"All"。 - Stephan Ronald
抱歉 - 我对 WPF 网格感到困惑了 - 如你所说,Windows.UI.Xaml.Controls.Grid 通过 ManipulationMode 启用了操作。 - Roger Rowland
ManipulationDelta 应该会触发多次。你能否发布你项目中相关的代码? - Murkaeus
1个回答

10

是的,我想我知道你想要什么。

假设你有这样的XAML:

<Grid Margin="50">
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    <Rectangle Fill="Blue" x:Name="MyRect" />
</Grid>

你想通过拖动矩形来在网格中移动它。

只需使用以下代码:

public MainPage()
{
    this.InitializeComponent();
    MyRect.ManipulationMode = ManipulationModes.TranslateX | ManipulationModes.TranslateY;
    MyRect.ManipulationDelta += Rectangle_ManipulationDelta;
    MyRect.ManipulationCompleted += Rectangle_ManipulationCompleted;
}

private void Rectangle_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)
{
    var _Rectangle = sender as Windows.UI.Xaml.Shapes.Rectangle;
    var _Transform = (_Rectangle.RenderTransform = (_Rectangle.RenderTransform as TranslateTransform) ?? new TranslateTransform()) as TranslateTransform;
    _Transform.X += e.Delta.Translation.X;
    _Transform.Y += e.Delta.Translation.Y;
}

private void Rectangle_ManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e)
{
    var _Rectangle = sender as Windows.UI.Xaml.Shapes.Rectangle;
    _Rectangle.RenderTransform = null;

    var _Column = System.Convert.ToInt16(_Rectangle.GetValue(Grid.ColumnProperty));
    if (_Column <= 0 && e.Cumulative.Translation.X > _Rectangle.RenderSize.Width * .5)
        _Rectangle.SetValue(Grid.ColumnProperty, 1);
    else if (_Column == 1 && e.Cumulative.Translation.X < _Rectangle.RenderSize.Width * -.5)
        _Rectangle.SetValue(Grid.ColumnProperty, 0);

    var _Row = System.Convert.ToInt16(_Rectangle.GetValue(Grid.RowProperty));
    if (_Row <= 0 && e.Cumulative.Translation.Y > _Rectangle.RenderSize.Height * .5)
        _Rectangle.SetValue(Grid.RowProperty, 1);
    else if (_Row == 1 && e.Cumulative.Translation.Y < _Rectangle.RenderSize.Height * -.5)
        _Rectangle.SetValue(Grid.RowProperty, 0);
}

针对这个问题:

enter image description here

希望我所提供的信息有所帮助!祝你好运!


谢谢您发布这个很棒的代码。它帮助我完成了我的作业!但是,我不太明白这是如何工作的,为什么在主页面构造函数中要使用两种操作模式(x和y)进行或运算?您能逐步解释一下您的代码吗?非常感谢!我真的很想理解正在发生的事情。 :) - Stefan Vasiljevic
GridView 外面有一个漂亮的拖放功能,有趣的是当你滑动并释放时它仍然保持移动状态,至少在设置了 ManipulationMode=”All” 时是这样的 :D - Totumus Maximus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接