简单闪烁文字

时间:2019-06-18 17:37:23

标签: c# wpf xaml

我正在尝试将一个闪烁的“ Hello World”文本与C#/ WPF中可能的代码最少的简单演示项目放在一起。我编写的内容可以编译并运行,但实际上并不会使文本闪烁(它基于一个计时器,该计时器每2秒触发一次并更改标签的可见性。有关文本为何不闪烁或效率更高的任何想法)方法是吗?代码:

using System;
using System.Timers;
using System.Windows;

namespace BlinkingText
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        static Timer _timer;
        static MainWindow window = new MainWindow();

    public MainWindow()
    {
        InitializeComponent();

        Start();
    }

    public static void Start()
    {
        var timer = new Timer(2000);
        timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
        timer.Enabled = true;
        _timer = timer;
    }

    public static void _timer_Elapsed(object sender, ElapsedEventArgs e)
    {

        if (window.HelloWorldLabel.Visibility == Visibility.Hidden)
        {
            Application.Current.Dispatcher.Invoke((Action)delegate
            {
                window.HelloWorldLabel.Visibility = Visibility.Visible;
            });
        }
        else
        {
            Application.Current.Dispatcher.Invoke((Action)delegate
            {
                window.HelloWorldLabel.Visibility = Visibility.Hidden;
            });
      }
    }
  }
}

1 个答案:

答案 0 :(得分:6)

您的应用程序中的文本不会闪烁,因为您在隐藏的MainWindow实例中更改了标签的可见性,这与您在屏幕上看到的不一样。

它是由创建的

//EditProject Component (component recieving props from ProjectDetails)

class EditProject extends Component {
  state = {
    title: "",
    content: ""
  };

  componentDidMount = () => {
    //Aquire proprs from React Router
    const title = this.props.location.state.title
    const content = this.props.location.state.content

    //Update the local state
    this.setState({
      title: title,
      content: content
    })
  }

但从未显示。

除此之外,您应该使用这样的DispatcherTimer:

static MainWindow window = new MainWindow();

您还可以在XAML中完全执行类似的操作,例如像这样:

public partial class MainWindow : Window
{
    private readonly DispatcherTimer timer =
        new DispatcherTimer { Interval = TimeSpan.FromSeconds(2) };

    public MainWindow()
    {
        InitializeComponent();

        timer.Tick += Timer_Tick;
        timer.Start();
    }

    private void Timer_Tick(object sender, EventArgs e)
    {
        HelloWorldLabel.Visibility = HelloWorldLabel.Visibility == Visibility.Visible
            ? Visibility.Hidden : Visibility.Visible;
    }
}