未处理的类型' System.InvalidOperationException'当我想通过backgroundworker在列表框中显示数据库数据时发生了
以下是代码:
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
private List<Product> products;
private void LstProduct_loaded(object sender, RoutedEventArgs e)
{
BackgroundWorker Worker = new BackgroundWorker();
Worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
Worker.DoWork += new DoWorkEventHandler(worker_DoWork);
Worker.RunWorkerAsync();
}
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
products = App.StoreDb.GetProducts();
}
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
LoadingGrid.Visibility = Visibility.Collapsed;
Lstproducts.ItemsSource = products;
}
}
答案 0 :(得分:0)
尝试使用
private void LstProduct_loaded(object sender, RoutedEventArgs e)
{
//create thread
ThreadStart myThreadStart = new ThreadStart(MyThreadRoutine);
Thread myThread = new Thread(myThreadStart);
myThread.ApartmentState = ApartmentState.STA;
myThread.Start();
}
//function
private void MyThreadRoutine()
{
this.Invoke((MethodInvoker)delegate {
products = App.StoreDb.GetProducts();
this.LoadingGrid.Visibility = Visibility.Collapsed;
this.Lstproducts.ItemsSource = products;
});
}