按钮内容和等待光标问题

时间:2014-12-29 19:26:17

标签: wpf xaml .net-4.0

我有一个带有一些代码的页面的WPF应用程序,如下所示

public partial class MyPage : Page
{
    public MyPage ()
    {
        InitializeComponent();
    }

    private void btnClose_Click(object sender, RoutedEventArgs e)
    {
        this.Cursor = Cursors.Wait;
        this.btnClose.Content = "Cancel";

        //  some long time consuming processing

        this.Cursor = Cursors.Arrow;
        this.btnClose.Content = "Close";
    }
  }

我在关闭按钮点击操作这里做了两件事,这会导致问题。在长时间处理之前,我将按钮上下文文本更改为取消。我也想改变整页的光标等待。处理完毕后,我将光标状态和按钮内容设置回原处。但是我面临两个问题。

  1. 当应用程序执行长时间运行时,我无法将按钮内容视为取消。它只是继续向我展示原始内容CLOSE。
  2. 光标仅在按钮上变为箭头。但是在页面的其余部分,我仍然保持相同的箭头光标。
  3. 任何想法如何解决这些问题?

2 个答案:

答案 0 :(得分:1)

这必须是一些重复的地方

public class WaitCursor : IDisposable
{
    private Cursor _previousCursor;

    public WaitCursor()
    {
        _previousCursor = Mouse.OverrideCursor;

        Mouse.OverrideCursor = Cursors.Wait;
    }

    #region IDisposable Members

    public void Dispose()
    {
        Mouse.OverrideCursor = _previousCursor;
    }

    #endregion
}

using (new WaitCursor())
{
     //  long blocking operation
}

答案 1 :(得分:1)

默认情况下,您的代码在UI线程上运行,因此在线程完成执行之前,不能在UI线程上执行任何其他操作(例如重新呈现UI)。

在代码完成执行之前有很多方法可以释放对UI线程的控制,但我发现最简单的方法是使用Task Parallel Library中的Task,它可以用来运行代码。单独的线程。

例如,

// this runs on the main UI thread
this.Cursor = Cursors.Wait;
this.btnClose.Content = "Cancel";

Task.Factory.StartNew(() =>
{
    // this code runs on a background thread

    // some long time consuming processing
})
.ContinueWith((e) =>
{
    // this code runs from the UI thread again
    this.Cursor = Cursors.Arrow;
    this.btnClose.Content = "Close";
});

应该注意,只能在UI线程上修改UI对象,这就是我将第二个UI更新放在任务的.ContinueWith(...)中的原因。另一种方法是使用Dispatcher来确保代码在UI线程上执行。如果你决定需要这个而不能通过Google找到一个简单的例子,请告诉我,我会在这里写一个。