c# - 为什么在 .NET 4.6 中更改 WPF DataGrid ItemsSource 如此缓慢?

标签 c# wpf datagrid

例如试试这个简单的 WPF 窗口:

<Window x:Class="MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="30" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>

        <TextBox Grid.Row="0" Text="{Binding Path=Filter, UpdateSourceTrigger=PropertyChanged}" />

        <DataGrid Grid.Row="1" ItemsSource="{Binding FilteredList}">
            <DataGrid.Columns>
                <DataGridTextColumn Binding="{Binding}" />
            </DataGrid.Columns>
        </DataGrid>

    </Grid>
</Window>

后面有这段代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;

public partial class MainWindow : Window, INotifyPropertyChanged
{
    List<string> items = new List<string>();
    string filter = string.Empty;

    public MainWindow()
    {
        InitializeComponent();
        DataContext = this;
        for (int i = 0; i < 100; i++) items.Add(i.ToString());
    }

    public IEnumerable<string> FilteredList
    {
        get { return this.items.Where(item => item.Contains(filter)).ToArray(); }
    }

    public string Filter
    {
        get { return filter; }
        set
        {
            if (filter != value)
            {
                filter = value;
                PropertyChanged(this, new PropertyChangedEventArgs("FilteredList"));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged = (s, e) => { };
}

网格中只有一百个字符串。文本框允许过滤字符串。

但是将例如 123 写入过滤器然后再次删除它会使应用程序卡住数秒。为什么这不是即时的?

编辑:在 .NET 4.5 中它确实是即时的,即使有 10'000 个项目。似乎是 .NET 4.6 中的回归?

最佳答案

问题是你每次都要替换整个集合。 您应该使用 CollectionViewSource 作为 DataGrid 的来源。 CollectionViewSource 接受过滤器表达式。因此,您可以根据原始 IEnumerable 创建一个 CollectionViewSource,并根据您的文本框值创建一个筛选器方法。然后调用你的CollectionViewSource的Refresh方法

关于c# - 为什么在 .NET 4.6 中更改 WPF DataGrid ItemsSource 如此缓慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40158922/

相关文章:

c# - C++ 作为 Windows 游戏编程的第一语言?

wpf - StyleSelector 并从 XAML 返回样式

c# - 在 WPF Datagrid 的新行中隐藏单元格

c# - 如何旋转 WPF 窗口?

c# - 不必要的 NotifyPropertyChanged 调用是否会导致性能问题?

datagrid - 将图像存储在 dojo 数据网格中

c# - 使用哪种轻量级数据网格?

c# - 类型 'Claims' 上的属性 'AspNetUser' 不是导航属性

c# - 报告服务器 Web 服务在哪里

c# - 无论错误如何,都使用 msbuild 任务真正启动/停止