datagrid在foreach循環中未更新。在下面的代碼中,datagrid在線程完成後更新,但不在之間。因爲我的foreach循環是另一個類。我知道,不知何故我必須實現BackgroundWorker.OnProgressChanged方法來更新進度,但無法弄清楚。使用backgroundworker更新datagrid WPF
XMAL FILE
<dg:DataGrid ItemsSource="{Binding}">
<dg:DataGrid.Columns>
<dg:DataGridTextColumn Binding="{Binding grade, Mode=TwoWay, IsAsync=True}" Header="Status"/>
</dg:DataGrid.Columns>
</dg:DataGrid>
GUI CLASS
public partial class GUIClass : Page
{
BackgroundWorker bgWorker = new BackgroundWorker();
public GUIClass()
{
InitializeComponent();
bgWorker.WorkerSupportsCancellation = true;
bgWorker.WorkerReportsProgress = true;
}
private void btnOK_Click(object sender, RoutedEventArgs e)
{
bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
bgWorker.ProgressChanged += new ProgressChangedEventHandler(bgWorker_ProgressChanged);
bgWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
bgWorker.RunWorkerAsync();
}
void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
ClassA cls= new ClassA();
cls.runprocess();
}
void bgWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
dataGrid1.Items.Refresh();
}
void bgWorker_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e)
{
....
.....
dataGrid1.Items.Refresh();
}
}
數據網格綁定
類public class BindClass
{
public bool staus{ set; get; }
public string grade{ set; get; }
}
ClassA的
class ClassA
{
public void runprocess()
{
foreach (var item in IEnumerable<BindClass>)
{
if(somecondition)
{
// I want to update datagrid at this stage so user can see it
item.grade="First"
}
}
}
}