【发布时间】:2010-01-05 15:16:37
【问题描述】:
我已经搜索了论坛,但我认为没有适合我的问题的问题...
我使用 BackgroundWorker 来处理非常耗时的操作。此操作完成后,应将按钮设置为启用,以便用户可以执行其他操作。
我正在使用 WPF 并且遵循 MVVM 模式,因此我无法直接访问此按钮。我必须在 BackgroundWorker_RunWorkerCompleted 事件处理程序中调用一个方法,该方法将表示按钮启用状态的属性设置为 true。
这一切都很好,除了一件事:按钮仅在我之后重绘,例如单击窗口(或最大化窗口,...)。这很烦人,花了我一整天的时间来摆脱这种行为,但我找不到解决方案……
BackgroundWorker_RunWorkerCompleted 事件处理程序如下所示:
void fileLoadBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
SetButtonToEnabled(); }
有人知道如何解决这个问题吗?
编辑:
按钮绑定到一个命令:
<Button Name="btnLoadTargetFile" Command="{Binding Path=LoadTargetCommand}" .../>
此命令是 Smith 在他的博客 (http://msdn.microsoft.com/en-us/magazine/dd419663.aspx) 中所述的 RelayCommand,如下所示:
public RelayCommand LoadTargetCommand
{
get
{
if (loadTargetCommand == null)
{
loadTargetCommand = new RelayCommand(param => this.OnRequestLoadFile(BusinessLogic.CustomTypes.TreeType.Target), param => this.CanLoadTarget);
}
return loadTargetCommand;
}
set { loadTargetCommand = value; }
}
this.CanLoadTarget 由 SetButtonToEnabled() 设置为 true;方法
编辑2:
以下代码“有效”:
fileLoadBackgroundWorker.RunWorkerAsync(argumentList);
while(fileLoadBackgroundWorker.IsBusy)
System.Windows.Forms.Application.DoEvents();
SetButtonToEnabled();
但那是某种非常危险和丑陋的代码......
【问题讨论】:
-
当您将属性设置为 true 时,您是否会引发
PropertyChanged事件(即您的视图模型是否正确实现了INotifyPropertyChanged)? -
如果我在 fileLoadBackgroundWorker.RunWorkerAsync() 之后调用该方法,一切正常,所以我认为这不是问题?!
-
出于好奇,您是否对表单的形状或边框(边框颜色等)进行了任何 WMI 修改?
-
klausbyskov 可能是正确的/有一个好点。那么-您是否正确实施了 INotifyPropertyChanged ? :)
-
@md5sum:不,我没有! @benjamin:是的,我愿意 ;-) ...我将代码从非线程环境移植到当前,在我们开始使用 BackgroundWorker 之前一切正常
标签: c# wpf backgroundworker