【问题标题】:DataGrid: Adding DataGridCellInfo-instances to the DataGrid.SelectedCells-collection is very slowDataGrid:将 DataGridCellInfo-instances 添加到 DataGrid.SelectedCells-collection 非常慢
【发布时间】:2014-02-18 01:21:51
【问题描述】:

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

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

不过,这段代码运行速度极慢。

MyDataGrid.Items 是 ItemCollection&lt;MyDataStructure&gt; 类型,包含大约 70,000 个项目。

MyDataGrid.SelectedCells 的类型为 IList&lt;DataGridCellInfo&gt;。 整个循环大约需要 30 秒。

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

【问题讨论】:

    标签: wpf linq datagrid


    【解决方案1】:

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

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

    【讨论】:

    • 这似乎是我处理它的最佳方式,谢谢。
    • 我对这个解决方案还有一个问题:这适用于选择整个 LINE,但是选择一个 COLUMN 怎么样?这意味着每行选择一项MyDataStructure。
    猜你喜欢
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    • 1970-01-01
    • 2021-03-01
    • 2018-08-17
    相关资源
    最近更新 更多