我的WPF应用程序中有SelectionChanged事件。我希望当更改选项卡以执行某些操作时,但首先我希望选项卡可以在>>操作开始之前改变。我正在使用后台工作人员来完成这项工作。我的代码是:
private void Tab_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (tab1.IsSelected)
{
//this line is not working
tabcontrol.SelectedIndex = 1;
wNetTest = new BackgroundWorker();
wNetTest.DoWork += new DoWorkEventHandler(worker_DoWork);
wNetTest.RunWorkerCompleted += worker_RunWorkerCompleted;
wNetTest.WorkerReportsProgress = true;
wNetTest.WorkerSupportsCancellation = true;
wNetTest.RunWorkerAsync();
}
}
void worker_DoWork(object sender, DoWorkEventArgs e)
{
//do the job
}
答案 0 :(得分:1)
您的问题是您的代码同步运行。因此,Tab_SelectionChanged
事件处理程序的每一行都将在之前运行,您将看到TabItem
更改。要解决此问题,您只需要异步运行长时间运行的进程。最简单的方法之一是:
private void Tab_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (tab1.IsSelected)
{
//this line is not working
tabcontrol.SelectedIndex = 1;
Task.Factory.StartNew(() => LongRunningMethod(parameter));
}
}
private void LongRunningMethod(object parameter)
{
// perform long running process here
}
parameter
输入参数是可选的...如果您不需要,请将其删除。