I have a DataGrid, which I bind in the constructor function of my UserControl (after InitializeComponent). I need to access some rows in it, so in the loaded event for the UserControl, I run:
DataGridRow row = (DataGridRow)myDataGrid.ItemContainerGenerator.ContainerFromIndex(rowIdx);
However whenever I do that, ItemContainerGenerator.ContainerFromIndex returns null. Seemed like the DataGrid wasn't fully generated yet, so to test/confirm that theory, I threw a button on the screen, and on the click event of the button, I ran that code again, and then sure enough, the row had a value. So, it's confirmed, when the UserControl's loaded event fires, it happens too early and I can't yet call ItemContainerGenerator.ContainerFromIndex for my DataGrid.
What event gets fired after loaded that I could use instead?
Note: I also tried this code that I found, but got the same results:
DataGridRow row = (DataGridRow)myDataGrid.ItemContainerGenerator.ContainerFromIndex(rowIdx);
if (row == null)
{
myDataGrid.UpdateLayout();
myDataGrid.ScrollIntoView(myDataGrid.Items[rowIdx]);
row = (DataGridRow)myDataGrid.ItemContainerGenerator.ContainerFromIndex(rowIdx);
}
And I also tried doing it in the DataGrid's loaded event but same results.
Thanks!
User controls, in WPF represented by the UserControl class, is the concept of grouping markup and code into a reusable container, so that the same interface, with the same functionality, can be used in several different places and even across several applications.
You can run that code at a lower DispatcherPriority than Loaded, such as Input
For example, the DataGrid's Loaded
event would contain something that looks like this:
MyDataGrid.Dispatcher.BeginInvoke(DispatcherPriority.Input,
new Action(delegate() { RunSomeFunction(); } ));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With