So, I have a WP8 app with multiple pages. I'm using ShakeGestures.dll in my app to detect the shakes.
On different pages (except the MainPage.xaml) I have separate-indepenent tasks (that involve the UI to be updated) that need to be performed whenever the "MinimumRequiredMovesForShake" is achieved.
The problem that I am facing is that, once I have traversed through the pages and return to my MainPage.xaml and shake my device, somehow the shake-detection event gets fired up!
Please note that the MainPage.xaml page does not require to detect the shakes as mentioned earlier.
When I repeatedly shake my device, thus satisfying the "MinimumRequiredMovesForShake" multiple times, all the tasks on the separate pages start getting executing!
According to me, either the shake-detection event involved somehow becomes "global" through out my app or the ShakeGestureHelper Instance needs to be "destroyed" when I navigate away from the page.
The code that I am using is:-
public Page1()
{
InitializeComponent();
ShakeGesturesHelper.Instance.ShakeGesture +=
new EventHandler<ShakeGestureEventArgs>(Perform_Shakeevent);
ShakeGesturesHelper.Instance.MinimumRequiredMovesForShake = 10;
ShakeGesturesHelper.Instance.Active = true;
}
private void Perform_Shakeevent(object sender, ShakeGestureEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
//Task to be perfomed here.
});
}
Well yes, as indicated by the XML documentation, ShakeGesturesHelper
is a singleton, and you access the single instance with ShakeGesturesHelper.Instance
. So you're registering a new event handler each time you use
ShakeGesturesHelper.Instance.ShakeGesture += ...
You should either unsubscribe each time you navigate away from a page, or check within each event handler whether the current page is the one that handler is interested in. Unsubscribing each time would probably be cleaner, as otherwise you'd also need to be careful not to resubscribe the next time the constructor is called.
Frankly it's not an ideal piece of design, and you might want to look into alternative shake gesture libraries to see if there's something better around...
See more on this question at Stackoverflow