DataGrid:将DataGridCellInfo实例添加到DataGrid.SelectedCells集合非常慢

时间:2014-01-27 09:14:05

标签: wpf linq datagrid

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

for (int i = 0; i < MyDataGrid.Items.Count; i++)
{
    MyDataGrid.SelectedCells.Add(new DataGridCellInfo(MyDataGrid.Items[i], column));
}

但这段代码运行得非常慢。

MyDataGrid.Items属于ItemCollection<MyDataStructure>类型,可容纳约70,000个项目。

MyDataGrid.SelectedCells的类型为IList<DataGridCellInfo>。 整个循环大约需要30秒。

有人可以解释为什么需要这么长时间吗? 此外,是否可以将此交换为LINQ查询?

1 个答案:

答案 0 :(得分:1)

当涉及大量数据时,访问SelectedCells/SelectedRows/SelectedColumns无效。因此,您无法将其更改为更多更好地工作。相反,我建议你使用样式和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>

MyDataStructure中的属性:

    private bool isItemSelected;
    public bool IsItemSelected
    {
        get { return isItemSelected; }
        set
        {
            isItemSelected = value;
            this.OnPropertyChanged("IsItemSelected");
        }
    }

最后循环遍历行:

foreach(var item in MyDataGrid.ItemsSource.Cast<MyDataStructure>())
{
    item.IsItemSelected = true;            
}
相关问题