Seems that it takes some time for a datatemplate to be set into a newly created item. This is simiar to How can I retrieve the DataTemplate (and specific objects) of an item in an ItemsControl? but that doesnt provide a satisfactory answer as well.
var newIndex = this.Items.Add(new object()); // new "data"
var newContainer = (ContentPresenter) this.ItemContainerGenerator.ContainerFromIndex(newIndex);
var uiElem = newContainer.FindName("txt");
The call to findname will return null, and so VisualTreeHelper.GetChildrenCount = 0. If I give it some time, the template is bound and all is well, but that’s non-deterministic. Does anyone know of an event or a way to force the template to be bound immediately?
Thanks
Applications can call ApplyTemplate() to guarantee that the visual tree of an element is complete. This guarantee step might be necessary if code will be checking the child elements in the tree.