Question

I am using C#, Silverlight, WP7.

I am trying to add an overlay to my app (similar to this) that overlays at the end of each series of LayoutUpdated events.

The first problem is that LayoutUpdated gets fired multiple times on each control event, whether it's just loading the app or scrolling or pivoting. I need to execute my code after the last LayoutUpdated event. According to this question, doing a BeginInvoke on the Loaded event will allow my code to wait for all events to finish firing. Is my understanding of this correct?

The other problem is updating the layout...on a LayoutUpdated event. This question says there will be an infinite loop of LayoutUpdated events firing, and that the solution is to set a hasChanged flag. But the flag needs to be reset by something so that on the next control event, right?

I'm confused how to implement a solution that solves both of these questions.
Thanks in advance.

Was it helpful?

Solution

I ended up solving both issues with one solution. I added a variable to keep track of the last time this method was called, and if it hasn't been called within a threshold (say 500ms), it adds the method to the dispatcher.

This ensures that whether the LayoutUpdated event is called once or multiple times, the method will execute once regardless. I initialize the variable to the beginning of time so that even the first call will execute.

Here is my code:

public class DesignChecker 
{
    private static DateTime lastCallTime = Datetime.MinValue;
    private static int minTimeSpan = 500; //set this threshold to your own needs
    public static void designChecker()
    {
        DateTime curTime = DateTime.UtcNow;
        TimeSpan span = curTime - lastCallTime;
        if (span.TotalMilliseconds < minTimeSpan)
        {
            lastCallTime = curTime;
        }
        else
        {
            lastCallTime = curTime;
            Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    doDesignCheck();
                });
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top