简体   繁体   中英

How to speed up WPF DataGrid?

The background: I have arbitrary query that is executed and then I fetch data -- array of records = arrays of objects. I would like to view them using DataGrid.

The problem: It does not feel that app is responsive enough. Switching from query to query is slow, it takes around 1-2 seconds to switch, and there are only ~20 records to display! I want to make the switch instantly, you click on "next query" and you get the results right away.

The code:

        // defining colums for a grid
        grid.Columns.Clear();

        int i = 0;
        foreach (var db_col in query.Names) // names of the colums
        {
            var col = new DataGridTextColumn();
            col.Header = db_col;
            col.Binding = new Binding(String.Format("Data[{0}]",i));
            grid.Columns.Add(col);
            ++i;
        }

        // adding rows to grid -- the culprit
        grid.Items.Clear();

        foreach (var db_row in query.Rows)
        {
            var row = new DataGridRow();
            row.Item = db_row;
            grid.Items.Add(row);
        }

I cannot see what I can other way -- I iterate over rows and I add them one by one. Rows are already in the memory, there is no database communication at this point. How do I know this (adding rows) is a reason for slowdown? Quite straightforward, I comment this out and the app becomes fast.

My box: Windows 7 Ultimate 32-bit, CPU Intel Core2Duo 2.66GHz, 2GB RAM.

Have you tried calling BeginInit and EndInit to stop the grid getting updated after each item is added?

grid.BeginInit();
grid.Items.Clear();

foreach (var db_row in query.Rows)
{
    var row = new DataGridRow();
    row.Item = db_row;
    grid.Items.Add(row);
}

grid.EndInit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM