这是因为您可能正在从 GUI 线程调用 StartReplay。只有在您的函数完成后,线程处理才会继续。换句话说,在您的功能完成之前,GUI 无法处理您的更改。当您在也是 gui 线程的按钮单击处理程序中进行更改时,您将退出您的函数并在该 gui 反映更改之后。这就是为什么第一种方法可以点击点击的原因。
您可以做的是启动工作线程并在那里进行修改,或者因为这似乎是类似动画的行为,请使用 Timers。
更新:
示例 1:
DispatcherTimer 在调用线程中执行回调。
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
namespace CanvasAnimation
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
DispatcherTimer uiTimer;
double directionDelta = 1.0;
public MainWindow()
{
InitializeComponent();
uiTimer = new DispatcherTimer(); //This timer is created on GUI thread.
uiTimer.Tick += new EventHandler(uiTimerTick);
uiTimer.Interval = new TimeSpan(0, 0, 0, 0, 1000/25); // 25 ticks per second
uiTimer.Start();
}
private void uiTimerTick(object sender, EventArgs e)
{
double currentLeft = Canvas.GetLeft(Kwadracik);
if (currentLeft < 0)
{
directionDelta = 1.0;
}
else if (currentLeft > 80)
{
directionDelta = -1.0;
}
currentLeft += directionDelta;
Canvas.SetLeft(Kwadracik, currentLeft);
}
}
}
示例 2:使用简单计时器
using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
namespace CanvasAnimation
{
/// <summary>
/// Interaction logic for WorkerTimer.xaml
/// </summary>
public partial class WorkerTimer : Window
{
Timer timer;
double directionDelta = 1.0;
public WorkerTimer()
{
InitializeComponent();
timer = new Timer(this.timerTick, this, 0, 1000 / 25); // 25 fPS timer
}
protected void timerTick(Object stateInfo)
{
//This is not a GUI thread!!!!
//So we need to Invoke delegate with Dispatcher
this.Dispatcher.Invoke(new MoveCanvasDelegate(this.moveCanvas), null);
}
protected delegate void MoveCanvasDelegate();
protected void moveCanvas()
{
//This function must be called on GUI thread!!!
double currentLeft = Canvas.GetLeft(Kwadracik);
if (currentLeft < 0)
{
directionDelta = 1.0;
}
else if (currentLeft > 80)
{
directionDelta = -1.0;
}
currentLeft += directionDelta;
Canvas.SetLeft(Kwadracik, currentLeft);
}
}
}
同样的技术适用于 BackgroundWorker 或其他非 GUI 线程。