datagrid在foreach循环中没有更新。在下面的代码中,一旦线程完成但数据网格之间没有更新。因为我的foreach循环是另一个类。我知道我必须以某种方式实现BackgroundWorker.OnProgressChanged方法来更新进度但无法弄清楚。
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();
}
}
DataGrid绑定类
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"
}
}
}
}
答案 0 :(得分:3)
为了在更改类的“grade”属性时更新datagrid,需要实现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));
}
}
}
注意 - 我已将属性名称从“grade”更改为“Grade”以遵循.NET约定。我相信你可以自己添加status属性的实现; - )
答案 1 :(得分:1)
我会寻求一个解决方案,其中dataGrid的ItemsSource是ObservableCollection
,使事情变得更容易,而且我认为你可以根据你所写的内容做到这一点。
像这样你不必去实现INotifyPropertyChanged事件处理程序的麻烦
(注意:ObservableCollections修改更新UI,而其他Collection类型则不更新)。这就是MS建议在dataGrid的doc中做的事情(尽管我不能把我的手放在我读过的那些文档上)