我有下面的代码示例。我想使用BackGroundWorker但是我有一个错误。
让我解释一下代码;
我该如何解决这个问题?
任何帮助表示感谢。
public class MainViewModel
{
public DataTable GridData{get;set;}
public void SaveExcel()
{
.
.
.
RefreshGridData();
}
public void RefreshGridData()
{
.
.
.
GridData = <selectedGridData>;
}
private void bgw_DoWork(object sender, DoWorkEventArgs e)
{
SaveExcel();
}
}
public class SaveExcel : ICommand
{
private MainViewModel viewModel;
public SaveExcel(MainViewModel viewModel)
{
this.viewModel = viewModel;
viewModel.PropertyChanged += (s, e) =>
{
if (CanExecuteChanged != null &&
(e.PropertyName == "SelectedA" || e.PropertyName == "SelectedB"))
{
CanExecuteChanged(this, new EventArgs());
}
};
}
public bool CanExecute(object parameter)
{
return (viewModel.SelectedA != null && viewModel.SelectedB != null);
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
viewModel.bgw.RunWorkerAsync();
}
}
public class SaveGrid : ICommand
{
private MainViewModel viewModel;
public SaveGrid(MainViewModel viewModel)
{
this.viewModel = viewModel;
viewModel.PropertyChanged += (s, e) =>
{
if (CanExecuteChanged != null && e.PropertyName == "GridData")
{
CanExecuteChanged(this, new EventArgs());
}
};
}
public bool CanExecute(object parameter)
{
return (viewModel.GridData.Rows.Count > 0);
}
public event EventHandler CanExecuteChanged;
.
.
.
.
}
答案 0 :(得分:4)
您需要在UI线程上调用刷新,在WPF中,您可以通过在代码中的适当位置调用Dispatcher.Invoke
来执行此操作。 E.g
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => RefreshGridData()));