我的窗户上有按钮。在用户点击按钮后,我希望我的应用程序为加载标签设置动画(带有旋转),在另一个线程中从数据库中获取一些数据。 从数据库动画加载数据后必须结束。任务看似简单,但不起作用。 问题在于动画无论我做什么动画,只有在不需要时从数据库加载后才会启动。
请帮助。这里有一些代码:
private void LoginButtonClick(object sender, RoutedEventArgs e)
{
Thread thread = new Thread(new ThreadStart(
delegate()
{
DispatcherOperation dispatcherOp =
this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(
delegate()
{
var da = new DoubleAnimation(360, 0, new Duration(TimeSpan.FromSeconds(1)));
var rt = new RotateTransform();
loadingLabel.RenderTransform = rt;
loadingLabel.RenderTransformOrigin = new Point(0.5, 0.5);
da.RepeatBehavior = RepeatBehavior.Forever;
rt.BeginAnimation(RotateTransform.AngleProperty, da);
}));
dispatcherOp.Completed += new EventHandler(DispatcherOpCompleted);
}));
thread.Start();
}
void DispatcherOpCompleted(object sender, EventArgs e)
{
//Loading From Database
}
答案 0 :(得分:3)
Dispatcher.Completed事件在主UI线程上执行。您的工作线程只是将调度程序操作排队并退出。而不是创建一个启动动画然后在Completed处理程序中加载数据库的线程,只需在主线程中启动动画,然后创建一个工作线程来进行数据库加载。
private void LoginButtonClick(object sender, RoutedEventArgs e)
{
var da = new DoubleAnimation(360, 0, new Duration(TimeSpan.FromSeconds(1)));
var rt = new RotateTransform();
loadingLabel.RenderTransform = rt;
loadingLabel.RenderTransformOrigin = new Point(0.5, 0.5);
da.RepeatBehavior = RepeatBehavior.Forever;
rt.BeginAnimation(RotateTransform.AngleProperty, da);
Thread thread = new Thread(new ThreadStart(LoadData));
thread.Start();
}
void LoadData()
{
//Loading From Database
// Use a Dispatch.BeginInvoke here to stop the animation
// and do any other UI updates that use the results of the database load
}