简体   繁体   中英

Force WPF UI thread to update on a task

Currently this code works, I suppose it doesn't work as intended because I haven't figured out how to force update the UI thread for every Opacity change in the button.

    private void BtnStart_Click(object sender, RoutedEventArgs e) {
        // Create a timer and add its corresponding event

        System.Timers.Timer timer = new System.Timers.Timer();
        timer.Elapsed += TimerFade_Elapsed;

        timer.Interval = 750;

        // Want a new thread to run this task on so
        // the main thread doesn't wait.

        Task task = new Task(() => timer.Start());
        task.Start();          
        //r.SingleThread();

    }

    private void TimerFade_Elapsed(object sender, System.Timers.ElapsedEventArgs e) {
        // Access UI thread to decrease Opacity on a button from a different thread.

        Dispatcher.Invoke(() => {
            if (btnStart.Opacity != 0.0) {
                btnStart.Opacity -= 1.0;
                // code here to force update the GUI.
            } else {
                System.Timers.Timer t;
                t = (System.Timers.Timer)sender;
                t.Stop();
            }
        });          

    }

The code works however visually, it doesn't. I suspect this has to do with me not updating the GUI when the changes are made.

The code provided is working fine. The value of opacity range from 0 to 1. You are setting it to 1 in first go, which will make the button disappear on first refresh. If you can change the following line

btnStart.Opacity -= 1.0;

To

btnStart.Opacity -= 0.1;

You will be able to see the button fading slowly.

PS: The best way to do this would be using StoryBoard(DoubleAnimation) as mentioned by @zack

You can simply use a storyboard. Create one in the resource of the object(such as Window / Page or whatever you have) and then call the storyboard from code behind.

Here's a sample :

 <Window.Resources>
 <Storyboard x:Key="FadeAnim">
        <DoubleAnimation Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:0.4"/>
    </Storyboard>
 </Window.Resources>

And call it from code behind like this :

 Storyboard sb = this.FindResource("FadeAnim") as Storyboard;
 Storyboard.SetTarget(sb, this.YourButton);
 sb.Begin();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM