我正在尝试在 WP8 中制作具有所有状态(按下、释放、移动)的触摸按钮,但TouchLocationState.Released
它不起作用。
这是我的代码:
类变量:
bool touching = false;
int touchID;
Button tempButton;
Button 是一个单独的类,具有在触摸时切换状态的方法。
Update 方法包含以下代码:
TouchCollection touchCollection = TouchPanel.GetState();
if (!touching && touchCollection.Count > 0)
{
touching = true;
foreach (TouchLocation location in touchCollection)
{
for (int i = 0; i < menuButtons.Count; i++)
{
touchID = location.Id; // store the ID of current touch
Point touchLocation = new Point((int)location.Position.X, (int)location.Position.Y); // create a point
Button button = menuButtons[i];
if (GetMenuEntryHitBounds(button).Contains(touchLocation)) // a method which returns a rectangle.
{
button.SwitchState(true); // change the button state
tempButton = button; // store the pressed button for accessing later
}
}
}
}
else if (touchCollection.Count == 0) // clears the state of all buttons if no touch is detected
{
touching = false;
for (int i = 0; i < menuButtons.Count; i++)
{
Button button = menuButtons[i];
button.SwitchState(false);
}
}
menuButtons 是菜单上的按钮列表。
在 touch 变量为 true 之后的单独循环(在 Update 方法中)
if (touching)
{
TouchLocation location;
TouchLocation prevLocation;
if (touchCollection.FindById(touchID, out location))
{
if (location.TryGetPreviousLocation(out prevLocation))
{
Point point = new Point((int)location.Position.X, (int)location.Position.Y);
if (prevLocation.State == TouchLocationState.Pressed && location.State == TouchLocationState.Released)
{
if (GetMenuEntryHitBounds(tempButton).Contains(point))
// Execute the button action. I removed the excess
}
}
}
}
用于切换按钮状态的代码工作正常,但我想要触发操作的代码不是。
location.State == TouchLocationState.Released
大多最终是错误的。(即使在我释放触摸之后,它的值也是TouchLocationState.Moved
)而且更令人恼火的是它有时会起作用!
我现在真的很困惑和卡住了好几天。这是正确的方法吗?如果是,那么我哪里错了?还是有其他更有效的方法来做到这一点?