C#WPF - 使用延迟显示文本

时间:2016-08-30 06:23:37

标签: c# wpf user-interface task delay

以下案例

按下按钮

显示文本框“已成功订购”

延迟2秒仍显示文字

延迟结束,文字更改/消失为“放置芯片”

问题:

使用线程睡眠它会在显示文本之前冻结整个UI,并且在延迟之后只显示第二个文本。有趣的是,播放更改文本后播放的声音但未显示文本。

使用Task(async / delay / await)它不等待延迟并且只显示两行,所以第一个文本在很短的时间内然后立即改为第二个文本。

使用任务(等待)程序崩溃。

使用Timer它与使用Task(异步或/和延迟)具有相同的效果。

使用while(时间,第二次+2秒)现在只是将新时间推进到时间,如果时间结束,它已经完成,但与Thread Sleep具有相同的效果 - 整个UI冻结。

<小时/> 也许有趣的是,有一些计时器在后台运行。

我尝试了很多我在这里找到的版本,但没有一个版本可行 - 也许是关于WPF的,所以我现在就问是否有人有WPF延迟的解决方案。

代码

        private void SendWithDelay()
        {
          //  close(); // Sets text back to "place your chip" but for here:
          tbPlace.Text = "Place your chip";
        }

        private void changeVisibilityForDelay()
        {
                // called by pressed button
                tbPlace.Text = "Successfully ordered";
                tbPlace.Visibility = Visibility.Visible;
                Task.Delay(2000).ContinueWith(t => SendWithDelay(), TaskScheduler.FromCurrentSynchronizationContext());
        }

3 个答案:

答案 0 :(得分:1)

(使用System.Windows.Threading;)
类似的东西:

private void startTimer(){
    Thread timerThread = new Thread(runTimer);
    timerThread.Start();
}

private async void runTimer(){
    await Task.Delay(2000);
    Dispatcher.BeginInvoke(new Action(() => updateScreen()));
}

private void updateScreen(){
    TextBox1.Text = "This is delayed";
}

答案 1 :(得分:1)

System.Threading.Timer的最小示例。还可以使用INotifyPropertyChanged Interface通过WPF Data Bindings更新用户界面中的更改。 XAML代码:

<Window x:Class="WpfTimerExample.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        SizeToContent="WidthAndHeight" WindowStartupLocation="CenterScreen" Title="WPF and System.Threading.Timer">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <StackPanel Grid.Row="0" Orientation="Vertical">
            <TextBlock Text="Text is: " />
            <TextBlock Text="{Binding Text}" />
            <TextBlock Text="TimeDiff: " />
            <TextBlock Text="{Binding TimeDiff}" />
        </StackPanel>
        <StackPanel Grid.Row="1">
            <Button Name="btnTimerExample" Content="Click to start Timer example"
                    Click="btnTimerExample_Click"/>
        </StackPanel>
    </Grid>
</Window>

代码:

using System;
using System.ComponentModel;
using System.Threading;
using System.Windows;

namespace WpfTimerExample
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        readonly TimeSpan TIMER_DUE_TIME = TimeSpan.FromSeconds(2);
        readonly TimeSpan TIMER_PERIOD = TimeSpan.FromMilliseconds(-1);

        DateTimeOffset _timeWhenButtonClicked;
        DateTimeOffset _timeWhenTimerFired;
        Timer _timer;
        string _Text;
        TimeSpan _TimeDiff;

        public event PropertyChangedEventHandler PropertyChanged = delegate { };

        public string Text
        {
            get { return _Text; }
            set { _Text = value; PropertyChanged(this, new PropertyChangedEventArgs("Text")); }
        }
        public TimeSpan TimeDiff
        {
            get { return _TimeDiff; }
            set { _TimeDiff = value; PropertyChanged(this, new PropertyChangedEventArgs("TimeDiff")); }
        }

        public MainWindow()
        {
            DataContext = this;
            Text = "Successfully ordered";
            InitializeComponent();
        }
        private void btnTimerExample_Click(object sender, RoutedEventArgs e)
        {
            Text = "Successfully ordered";
            TimeDiff = TimeSpan.Zero;

            _timeWhenButtonClicked = DateTimeOffset.UtcNow;
            // If there is no timer
            if (_timer == null) {
                // Create and start timer. 
                // Call TimerHandler just one time after 2 seconds
                _timer = new Timer(TimerHandler, null, TIMER_DUE_TIME, TIMER_PERIOD);
            }
            else // if exist, just restart it
                _timer.Change(TIMER_DUE_TIME, TIMER_PERIOD);
        }
        private void TimerHandler(object state)
        {
            _timeWhenTimerFired = DateTimeOffset.UtcNow;
            Text = "Place your chip";
            TimeDiff = _timeWhenTimerFired - _timeWhenButtonClicked;
        }
        protected override void OnClosed(EventArgs e)
        {
            if (_timer != null)
                _timer.Dispose();
        }
    }
}

答案 2 :(得分:1)

在这种情况下,您可以尝试使用DispatcherTimer。请尝试以下示例  添加两个按钮和一个文本框。                          在后面的代码中添加

DispatcherTimer obj = new DispatcherTimer();

    private void button_Click(object sender, RoutedEventArgs e)
    {
        textBox.Text = "Successfully ordered";
        obj.Interval = new TimeSpan(0, 0, 2);
        obj.Start();
        obj.Tick += Obj_Tick;
    }

    private void Obj_Tick(object sender, EventArgs e)
    {
        textBox.Text = "Place your chip";
        obj.Stop();
    }