我们为了让DataGrid在后台数据更新之后自动刷新显示,一般都用ObservableCollection<T>作为数据源。这个在数据量小的时候没有什么问题,如果数据量大的时候对性能会有影响,因为每次在向ObservableCollection插入数据的时候,都要更新UI。我做了一个实验,向ObservableCollection中添加5000行数据,到DataGrid加载数据完毕,总共用了1s。
有时候为了效率,我们更倾向于使用类似于.Net Framework里面的绑定方式,不需要自动更新,我们后台修改了数据之后,手动在代码里面重新绑定。比如我们用一般的List<T>作为数据源,然后在更新了数据源之后重新绑定,你会发现DataGrid并没有更新。
这里有一个trick需要注意一下,在重新绑定数据之前,需要先把ItemSource设为null, 然后再设为我们更新过的数据源。
new class Person
{
public string Name {get;set;}
public int Age {get;set;}
public string Address {get;set;}
}
//.... ....
//Update data source
List<Person> Persons = new List<Person>();
for(int i=0;i<5000;i++)
{
Persons.Add(new Person()
{
Name="Jacky Chen",
Age = 64,
Address ="Quenen street, Hong Kong, Chinak",
});
}
MyDataGrid.ItemSource = null; //This is needed before re-bind data
//re-bind DataGrid, but will not take effect if did not set ItemSource=null before
MyDataGrid.ItemSource = Persons;
用普通List更新数据源之后,手动代码重新绑定,这里5000行用时20ms, 大家看到差异了把,50倍的差异。
另外我在实际开发过程中还放过一个错,导致DataGrid奇慢无比,而且非常占据内存。1000行居然用了5,6s时间,占据400M左右的内存。最后发现是ScrollViewer导致的,我把DataGrid放在ScrollViewer里面,目的是数据行/列比较多的时候可以出现滚动条。但是这个导致了速度奇慢,内存占据非常告,把ScrollViewer去掉之后就没有问题了。其实DataGrid自己会有滚动条的,根本不需要再套一个ScrollViewer。
希望给遇到通用坑的朋友一些提示。
<!-- ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" -->
<controls:DataGrid Name="MyDataGrid" Grid.Row="1" AutoGenerateColumns="False"
Loaded="MyDataGrid_Loaded"
>
<controls:DataGrid.Columns >
<controls:DataGridTemplateColumn Header="Template">
<controls:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock SizeChanged="TextBlock_SizeChanged" HorizontalAlignment="Stretch" Text="{Binding cName}"/>
</DataTemplate>
</controls:DataGridTemplateColumn.CellTemplate>
</controls:DataGridTemplateColumn>
</controls:DataGrid.Columns >
</controls:DataGrid>
<!--/ScrollViewer-->
517

被折叠的 条评论
为什么被折叠?



