I have seen solutions to a very similar issue, yet it doesn't translate to mine. (Namely, this article: http://blogs.msdn.com/wpfsdk/archive/2007/04/16/how-do-i-programmatically-interact-with-template-generated-elements-part-ii.aspx)
My ItemsControl is bound to an observable collection, which can have items dynamically added to it.
When I add an item to the observable collection, the templated item renders properly in my itemscontrol, but I can't figure out how to access it. My my observable colleciton changed code, I am trying to access information about. I am using a custom DataTemplateSelector to return one of 3 different dataTemplates, based on the item's data in the collection.
Here is an outline of my ItemsControl XAML:
<ItemsControl Name="myItemsControl" ItemTemplateSelector="{StaticResource myTempSelector}">
<ItemsControl.Template>
<ControlTemplate TargetType="ItemsControl">
<ItemsPresenter/>
</ControlTemplate>
</ItemsControl.Template>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel></StackPanel>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
The solutions I've seen suggest using ItemContainerGenerator.ContainerFromItem(xxx)
In this examples, they are always looking for information about a ListBox or ComboBox (which inherit from ContentControl). However, when I call (in my code-behind) myItemsControl.ItemContainerGenerator.ContainerFromItem(xxx)
, I receive a ContentPresenter, rather than the ContentControl I expect.
Then, when I try to access the ContentTemplate of this ContentPresenter, I get a null object exception.
I have a hunch that the rest of my troubles descend from there.
All I want to do is find a textbox from the datatemplate in my newly created control, and give it focus.
Help! :-)