Perform actions after WPF DataGrid data is completely bound

alitheg Source

I have an old Windows Forms application at work which I am converting to WPF. As part of this, there is a button which, when clicked, creates a brand new DataGridView and adds it to the page, binding it to data from a SQL query. This data is bever written back to the database, but a new column is added to the end of the data with a checkbox on it, and when the checkbox is changed the ID from the row is passed into another method along with the state of the checkbox.

In WPF, I have the dynamic grid creation working, and the data binding. Having found I couldn't directly add the column to the DataGrid itself, I've added it to the source DataSet table before binding. This works and whos all the data along with a checkbox for each row. However, I can't get an event to fire when the an individual checkbox is clicked.

I have managed to find some code at http://forums.silverlight.net/t/11547.aspx, which causes the row to commit whenever the checkbox is changed, as my code to pass the ID and bool value currently resides in an EditEnding event. Initially the UpdateSourceTrigger was added to each checkbox by looping over each row in the checkbox column during the "Loaded" event of the DataGrid, but this is now failing, and after some internet searching it seems to be because "Loaded" doesn't guarantee that the data has finished binding, and I'm finding that DataGrid.Items contains more items than there are containers in the grid at the point the event fires. Below is the code I'm trying to use to bind the UpdateTrigger, but at row 32 suddenly the ContainerFromIndex method returns null. There are 69 items in dgvNew.Items at that point.

dgvNew.Loaded += new RoutedEventHandler(delegate(object sender, RoutedEventArgs e)
        {
            for (var i = 0; i < dgvNew.Columns.Count; i++)
            {
                DataGridBoundColumn column = dgvNew.Columns[i] as DataGridBoundColumn;
                if (column != null && column.Header.ToString() == "HasPermission")
                {
                    for (var j = 0; j < dgvNew.Items.Count; j++)
                    {
                        DataGridRow row = (DataGridRow)dgvNew.ItemContainerGenerator.ContainerFromIndex(j);
                        UpdateSourceTriggerHelper.SetUpdateSourceTrigger(column.GetCellContent(row), true);
                    }
                }
            }
        });

I've also tried wrapping the for loop up in an event handler for the ItemContainerGenerator.StatusChanged and checking that Status is ItemsGenerated, but that didn't help either.

Can anyone see where I'm going wrong, in code or in understanding?

wpfdatagrid

Answers

comments powered by Disqus