Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Event Happens After Loaded For A WPF UserControl?

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!

like image 832
Nullqwerty Avatar asked Aug 10 '11 19:08

Nullqwerty


People also ask

What is UserControl WPF?

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.


1 Answers

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(); } ));
like image 138
Rachel Avatar answered Sep 27 '22 23:09

Rachel