简体   繁体   中英

WPF DataGrid - Change value row by row in “real time”

I'm creating this DataGrid:

DataTable _dt = new DataTable("MyDataTable");
_dt.Columns.Add("ID", typeof(int));
_dt.Columns.Add("File", typeof(string));
_dt.Columns.Add("Folder", typeof(string));
_dt.Columns.Add("Status", typeof(string));
_dt.Columns["ID"].AutoIncrement = true;
_dt.Columns["ID"].AutoIncrementSeed = 1;
_dt.Columns["ID"].AutoIncrementStep = 1;

FilesGridView.SelectionMode = DataGridSelectionMode.Extended;

FilesGridView.ItemsSource = _dt.DefaultView;

and then populating it with a list of file paths.

When I hit the Process button, I want to loop through all the rows in the grid and change the value of the Status column, row by row .

So I've written this:

private void ProcessButton_Click(object sender, RoutedEventArgs e)
{
    foreach (DataRowView row in FilesGridView.ItemsSource)
    {
        row["Status"] = "Processing...";
        System.Threading.Thread.Sleep(2000);    //letting 2 sec pass as a test
    }
}

but what happens is that it starts calculating and after 2 seconds * the iterations in the loop are elapsed, the table changes all at once.

What I was looking for was that entering the foreach loop, it was changing the displayed value first row, then waiting 2 sec and changing the displayed value of the second row, and so on.

What am I missing? How do I achieve that?

If you need to display the progress on updates while the loop is running, you just need a bit of asynchronous programming. Just make your event handler method asynchronous and run the loop inside a Task, like this:

private async void Process_OnClick(object sender, RoutedEventArgs e) {
    await Task.Run(async () => {
        foreach (DataRowView row in this.FilesGridView.ItemsSource) {
            row["Status"] = "Processing...";
            await Task.Delay(2000);
        }
    });
}

I tested the code in this project. Check the MainWindow. Add some items during execution in the DataGrid and then press the button.

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