c# - 在 WPF 中实现暂停

标签 c# wpf dependency-properties delay

这里有一个简单的 WPF 程序:

<!-- Updater.xaml -->
<Window x:Class="Update.Updater"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        DataContext="{Binding RelativeSource={RelativeSource Self}}">
    <Grid>
        <StackPanel>
            <Button Click="Button_Click" Height="50"></Button>
            <Label Content="{Binding Label1Text}" Height="50"></Label>
            <Label Content="{Binding Label2Text}" Height="50"></Label>
        </StackPanel>
    </Grid>
</Window>

// Updater.xaml.cs
using System.Threading;
using System.Windows;

namespace Update
{
    public partial class Updater : Window
    {
        public Updater()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            Label1Text = "It is coming...";
            Thread.Sleep(3000);
            Label2Text = "It is here!";
        }

        public string Label1Text
        {
            get { return (string)GetValue(CategoryProperty); }
            set { SetValue(CategoryProperty, value); }
        }

        static readonly DependencyProperty CategoryProperty = DependencyProperty.Register("Label1Text", typeof(string), typeof(Updater));

        public string Label2Text
        {
            get { return (string)GetValue(Label2TextProperty); }
            set { SetValue(Label2TextProperty, value); }
        }

        static readonly DependencyProperty Label2TextProperty = DependencyProperty.Register("Label2Text", typeof(string), typeof(Updater));
    }
}

目的是当你点击按钮时,第一个标签显示It is coming...。然后程序休眠 3 秒,最后第二个标签显示 It is here!。但是,下面的简单实现不起作用。如果运行它并单击按钮,会发生以下情况:程序休眠 3 秒钟,然后两个标签文本同时显示。您知道如何更正程序以使其按预期运行吗?

最佳答案

Button_Click 由 UI 线程调用,您不应在其中做任何需要超过几毫秒的事情,更不用说休眠 3 秒了。在此期间不会处理消息,您的界面没有响应,并且您的应用程序被系统视为“挂起”。

所以,那个长时间的处理任务应该由另一个线程来处理。

类似的东西(未经测试):

private void Button_Click(object sender, RoutedEventArgs e)
{
    Label1Text = "It is coming...";

    var backgroundWorker = new BackgroundWorker();

    backgroundWorker.DoWork += (s,e) => { Thread.Sleep(3000); }
    backgroundWorker.RunWorkerCompleted += (s,e) => { Label2Text = "It is here!"; }
    backgroundWorker.RunWorkerAsync();
}

链接:

BackgroundWorker

Build More Responsive Apps With The Dispatcher

关于c# - 在 WPF 中实现暂停,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10383116/

相关文章:

c# - 平面 xml 文件 C#

c# - 来自 C# 的多个 CMD 命令?

c# - 选择组合框期间出现空引用异常

wpf - VirtualizingStackPanel 与虚拟化列表

c# - WPF 绑定(bind)到变量/DependencyProperty

c# - WebBrowser Navigate 和 InvokeScript 的流程

c# - 使用 Quartz 每天随机触发一个函数

具有可变数量的按钮/形状的 WPF DataGrid 列

wpf - 如何取消动画 WPF DependencyProperty?

c# - 更新依赖属性/附加属性中的普通属性,