2011-02-01 125 views
0

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" 
      } 
      } 
    } 
} 

回答

3

爲了在更改類的'grade'屬性時更新數據網格,它需要實現INotifyPropertyChanged。嘗試更新類,如下所示:

public class BindClass : INotifyPropertyChanged 
{ 
private string _grade; 

public string Grade 
{ 
    get { return _grade; } 
    set 
    { 
    if (_grade == value) 
     return; 

    _grade = value; 
    OnPropertyChanged("Grade"); 
    } 
} 

public event PropertyChangedEventHandler PropertyChanged; 

protected void OnPropertyChanged(string property) 
{ 
    if (PropertyChanged!=null) 
    { 
    PropertyChanged(this, new PropertyChangedEventArgs(property)); 
    } 
} 
} 

注意 - 我已經從「品位」到「級」更改屬性的名稱遵循.NET約定。我相信你可以添加狀態屬性自己的執行;-)

1

我會去一個解決方案,DataGrid的ItemsSource時是ObservableCollection,使事情變得更容易,而且我認爲你可以做到這一點,你的情況從你寫的是什麼。

這樣你就不必去執行INotifyPropertyChanged的事件處理程序

的麻煩(注:ObservableCollections修改更新UI,而其他集合類型不)。這是MS建議在dataGrid的文檔中做的事情(雖然我不能把我的手放在我讀過的文檔的位上)