1

目前这段代码有效,我想它没有按预期工作,因为我还没有弄清楚如何为按钮中的每个不透明度更改强制更新 UI 线程。

    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();
            }
        });          

    }

该代码在视觉上有效,但事实并非如此。我怀疑这与我在进行更改时没有更新 GUI 有关。

4

2 回答 2

0

提供的代码工作正常。opacity 的值范围从 0 到 1。您在第一次将其设置为 1,这将使按钮在第一次刷新时消失。如果您可以更改以下行

btnStart.Opacity -= 1.0;

btnStart.Opacity -= 0.1;

您将能够看到按钮慢慢消失。

PS:最好的方法是使用 @zack 提到的 StoryBoard(DoubleAnimation)

于 2019-01-14T07:39:01.187 回答
0

您可以简单地使用故事板。在对象的资源中创建一个(例如Window/Page或您拥有的任何东西),然后从后面的代码中调用情节提要。

这是一个示例:

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

并像这样从后面的代码中调用它:

 Storyboard sb = this.FindResource("FadeAnim") as Storyboard;
 Storyboard.SetTarget(sb, this.YourButton);
 sb.Begin();
于 2019-01-14T07:50:30.827 回答