开发者

Make silverlight page reload every 5 seconds

开发者_StackOverflow中文版

I have created a page in silverlight that contains a button, by clicking this button it will start a timer, with each timer tick it creates a rectangle in the page, each rectangle is next to another till the page is full with rectangles.

My question is how to make the page reload when its full with rectangles?

Ps. I created the page with code(.cs) NOT .xaml, and I also want to make it reload in silverlight code (.cs) NOT .xaml


First off, you do not want to reload the page (In the traditional sense) as this will restart your silverlight app.

Have you looked at the WriteableBitmapEx (http://writeablebitmapex.codeplex.com/) ? You can use this to draw your rectangles and then clear the screen.

If this doesn't help, please advise how you are drawing your rectangles.


Look at the System.Threading.Timer class. It allows you to schedule tasks in intervals. An example which reloads the whole page (you should consider to clear only your page as Pino suggested):

public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();
        timer = new Timer(TimerElapsed);
    }

    // hold the timer in a variable to prevent it from being garbage collected
    private Timer timer = null;

    private void TimerElapsed(object state)
    {
        // important: this line puts the timer call into UI thread
        Dispatcher.BeginInvoke(() => {
            // your code goes here...
            // reload the page (this will reload the app and stop the timer!)
            HtmlPage.Window.Eval("location.reload()");
        });
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        // start the timer in 1 second and repeat every 5 seconds
        timer.Change(1000, 5000);
    }
}

Watch the comments in the code. It is necessary to store the Timer in a variable at class scope. Otherwise it wouldn't be referenced and could be garbage collected. If you want to change something on the page in the timed operation, you must put it into the UI thread using the Dispatcher object. You will get an exception if you don't do it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜