Accessing controls in newly added listview row WPF C#
I have a listview in WPF and C# that uses an ObservableCollection to populate the data. When a certain event is fired, I call a function to insert a new row into the collection. I then need to access the controls in that row.
The problem i am having is that after i insert the row, and I try to loop through the listview rows, this row is displaying as null in my loop.
if (addNewNote)
{
_resultsCollection.Insert(0, new ResultsData
{
开发者_JAVA技巧 Notes = "Data to Insert",
// ... rest of fields
});
} // end if (addNewNote)
for (int currRowIndex = 0; currRowIndex < this.ResultsList.Items.Count; currRowIndex++)
{
System.Windows.Controls.ListViewItem currRow =
(System.Windows.Controls.ListViewItem)this.ResultsList.ItemContainerGenerator.ContainerFromIndex(currRowIndex);
if (currRow != null)
{
System.Windows.Controls.TextBox tb = FindByName("EditNotesTextBox", currRow) as System.Windows.Controls.TextBox;
// do stuff with controls ...
}
}
Here currRow is always null, when the currRowIndex is zero.
This should not be the case, because i have just added it. Is it because I am trying to access it in the same function where I insert it, and the listview has not yet been updated? I am able to access every other row in the listview. Is there a better solution? Thanks!
In order to newly added item to be accessible first the container for that item (UI) needs to be generated by ItemContainerGenrator
. The generation is done on the same (UI) thread, so you cannot access containers right after you have added an item.
You can subscribe to ResultsList.ItemContainerGenerator.StatusChanged
event and in the event handler check if the status is GeneratorStatus.ContainersGenerated
then you can obtain the container.
ResultsList.ItemContainerGenerator.StatusChanged += OnGeneratorStatusChanged;
...
private void OnGeneratorStatusChanged(object sender, EventArgs e)
{
if (MyListBox.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
{
// Access containers for newly added items
}
}
Please refer to this article by Dr.WPF that describes how it works in detail.
精彩评论