【发布时间】:2015-09-01 17:50:52
【问题描述】:
我在 windows phone 8 中工作,并且在 Pivot 控件中有两个枢轴项。 如何检测我是向右还是向左滑动?
【问题讨论】:
-
我已经从问题的标题中删除了一个标签 - 请注意大多数情况下的问题shouldn't include tag in their title.
标签: windows-phone-8 pivot
我在 windows phone 8 中工作,并且在 Pivot 控件中有两个枢轴项。 如何检测我是向右还是向左滑动?
【问题讨论】:
标签: windows-phone-8 pivot
第 1 步:在您的解决方案中添加 Microsoft.Phone.Controls.Toolkit
Step2:在 xaml 中添加 Microsoft.Phone.Controls.Toolkit 引用,如下所示:
xmlns:tolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
Step3:像这样创建手势监听器轻弹事件:
<Grid x:Name="LayoutRoot" Background="Transparent">
<tolkit:GestureService.GestureListener>
<tolkit:GestureListener Flick="GestureListener_Flick"></tolkit:GestureListener>
</tolkit:GestureService.GestureListener>
<!--Pivot Control-->
<controls:Pivot Title="MY APPLICATION">
<!--Pivot item one-->
<controls:PivotItem Header="item1">
<Grid/>
</controls:PivotItem>
<!--Pivot item two-->
<controls:PivotItem Header="item2">
<Grid/>
</controls:PivotItem>
</controls:Pivot>
</Grid>
第 4 步:在您的 cs 页面中添加以下代码:
private void GestureListener_Flick(object sender, FlickGestureEventArgs e)
{
if (e.Direction.ToString() == "Horizontal") //Left or right
{
if (e.HorizontalVelocity > 0) //Right
{
}
else //Left
{
}
}
}
【讨论】:
对于简单的情况(如果您有超过 2 个数据透视项目),您可以使用您的数据透视的 SelectionChanged 事件 - 提供变量,您将在其中保存最后一个 SelectedIndex 并在更改后检查它是右还是左:
myPivot.SelectionChanged+=myPivot_SelectionChanged; // in your MainPage()
private int lastSelected = 0;
private void myPivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if ((lastSelected + 1 == myPivot.SelectedIndex) ||
(myPivot.SelectedIndex == 0 && lastSelected == myPivot.Items.Count - 1))
{
// moved right
}
else
{
// moved left
}
lastSelected = myPivot.SelectedIndex;
}
对于简单的情况它应该可以工作,对于更复杂的情况,您可以使用TouchPanel 或其他解决方案。
【讨论】:
您可以使用 EventArgs 参数 e 而不是使用 Items.Count 来确定 Pivot Items Collection 中的最后一个索引和使用以下选定的索引:
private void pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
// Casting e.AddedItems and e.RemovedItems to the PivotItem type to get
// the Selected Pivot and the Last Selected Pivot
var selectedPivot = (PivotItem) e.AddedItems[0];
var lastPivot = (PivotItem) e.RemovedItems[0];
// Getting indices using the ItemCollection of the pivot
int selectedIndex = pivot.Items.IndexOf(selectedPivot);
int previousIndex = pivot.Items.IndexOf(lastPivot);
if (selectedIndex < previousIndex)
{
// user swiped to the right
}
else
{
// user swiped to the left
}
}
即使您只有两个枢轴,这也会对您有所帮助。
【讨论】:
所有人都做得很好,但是当我们单击一个按钮来向前和向后导航 PivotItems 时我们会做什么。
所以只需将以下代码放在两个按钮中,即前进和后退。 您可以通过设置 Pivot.SelectedIndex 轻松实现此目的
前锋
if(pivotName.SelectedIndex < (pivotName.Items.Count - 1))
pivotName.SelectedIndex++;
else
pivotName.SelectedIndex = 0;
向后
if(pivotName.S electedIndex > 0)
pivotName.SelectedIndex--;
else
pivotName.SelectedIndex = pivotName.Items.Count - 1;
【讨论】: