Wpf DataGrid:将DataGridCellInfo实例添加到DataGrid.SelectedCells-collection非常缓慢

Wpf DataGrid:将DataGridCellInfo实例添加到DataGrid.SelectedCells-collection非常缓慢,wpf,linq,datagrid,Wpf,Linq,Datagrid,在WPF数据网格中,我尝试使用以下代码选择给定列中的所有单元格 for (int i = 0; i < MyDataGrid.Items.Count; i++) { MyDataGrid.SelectedCells.Add(new DataGridCellInfo(MyDataGrid.Items[i], column)); } for(int i=0;i

在WPF数据网格中,我尝试使用以下代码选择给定列中的所有单元格

for (int i = 0; i < MyDataGrid.Items.Count; i++)
{
    MyDataGrid.SelectedCells.Add(new DataGridCellInfo(MyDataGrid.Items[i], column));
}
for(int i=0;i
不过,这段代码运行速度非常慢

MyDataGrid.Items
属于
ItemCollection
类型,可容纳约70000项

MyDataGrid.SelectedCells
的类型为
IList
。 循环总共大约需要30秒

有人能解释一下为什么要花这么长时间吗?
另外,是否可以将其交换为LINQ查询

对于大型数据集,访问
SelectedCells/SelectedRows/SelectedColumns
无论如何都是低效的。所以你不能改变它来更好地工作。相反,我建议您使用style和
DataTrigger
。要应用此解决方案,您必须扩展
MyDataStructure
并添加
IsSelected
属性。然后通过应用特定的样式来模拟选择:

<Style x:Key="dataGridSelectableCellStyle" TargetType="{x:Type DataGridCell}" BasedOn="{StaticResource {x:Type DataGridCell}}">
    <Style.Triggers>
        <DataTrigger Binding="{Binding IsItemSelected}" Value="True">
            <Setter Property="Background" Value="Gey"/>
            <Setter Property="Foreground" Value="White"/>
        </DataTrigger>
    </Style.Triggers>
</Style>
最后通过行循环:

foreach(var item in MyDataGrid.ItemsSource.Cast<MyDataStructure>())
{
    item.IsItemSelected = true;            
}
foreach(MyDataGrid.ItemsSource.Cast()中的var项)
{
item.IsItemSelected=true;
}

这似乎是我处理此问题的最佳方式,谢谢。对于此解决方案,我还有一个问题:这对于选择整行非常有效,但是选择一列如何?这意味着每行选择一项
MyDataStructure
foreach(var item in MyDataGrid.ItemsSource.Cast<MyDataStructure>())
{
    item.IsItemSelected = true;            
}