开发者

Silverlight Button Click

开发者 https://www.devze.com 2023-03-01 08:00 出处:网络
I\'m having problems getting the Silverlight Button Click event to immediately update a control\'s UI element and then continue doing some other process.For example, update the text of a control 开发者

I'm having problems getting the Silverlight Button Click event to immediately update a control's UI element and then continue doing some other process. For example, update the text of a control 开发者_如何学Goand then do some process. I've tried calling the UpdateLayout() method but that doesn't help.

Here is some sample code:

private void button1_Click(object sender, RoutedEventArgs e)
{
    textBlock1.Text = "Testing";
    textBlock1.UpdateLayout();            
    UpdateLayout();
    Thread.Sleep(2000);
    textBlock1.Text = "Done";
}

In that sample, the textBlock1 control will never display the text "Testing".


It's because you've blocked the UI thread with your Sleep statement which means that the text block won't update until after it's completed, but by that time you've set the text to "Done".


This doesn't work. The UI will block when you do not exit the method. This is why in Silverlight you usually do everything asynchronously:

private void button1_Click(object sender, RoutedEventArgs e)
{
   textBlock1.Text = "Testing";
   var myTask = /* ... */
   myTask.Completed += new FancyDelegate(myTask_Completed);
}

private void myTask_Completed(object sender, RoutetEventArgs e)
{
   textBlock1.Text = "Done.";
}

If your tasks do not have asynchronous functions, just wrap them. But be reminded, that when you want to change your textBlock1.Text property from another thread, you must invoke it with the Dispatcher.

0

精彩评论

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