我尝试在另一个线程上添加加载数据模型并将项目加载到列表框,因为将 50 个项目加载到列表框需要很长时间(大约 5 秒)。
我对 BackgroundWorker 有问题,它显示错误 Invalid cross-thread access
他是 Inbox.xaml 的代码
public Inbox()
{
InitializeComponent();
DataContext = App.ViewModel;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
ProgressIndicator progress = new ProgressIndicator
{
IsVisible = true,
IsIndeterminate = true,
Text = "Načítání"
};
SystemTray.SetProgressIndicator(this, progress);
SystemTray.IsVisible = true;
BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
backgroundWorker.RunWorkerAsync();
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
LoadData();
}
void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
else
{
SystemTray.IsVisible = false;
}
}
private void LoadData()
{
try
{
(this.DataContext as MainViewModel).LoadInboxData();
}
finally
{
TasksListBox.ItemsSource = (this.DataContext as MainViewModel).Tasks;
}
}
我究竟做错了什么?