How can I get the DataTemplate (and specific objects) of an element in an ItemsControl?

I saw solutions to a very similar problem, but this does not translate into 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 tied to an observable collection, which may contain items dynamically added to it.

When I add an item to the monitored collection, the template item is correctly displayed in the itemscontrol control, but I cannot figure out how to access it. My observable team changed the code, I'm trying to access information. I use my own DataTemplateSelector to return one of three different data patterns based on the data in the collection.

Here is the outline of my ItemsControl XAML control:

<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 these examples, they are always looking for information about ListBox or ComboBox (which inherit from ContentControl). However, when I call (in my code) myItemsControl.ItemContainerGenerator.ContainerFromItem(xxx) , I get the ContentPresenter, not the ContentControl, which I expect.

Then, when I try to access the ContentTemplate of this ContentPresenter, I get an exception from the null object.

I have a suspicion that the rest of my problems come from there.

All I want to do is find the text box from the datatemplate in my newly created control and give it focus.

Help!: -)

+4
source share
1 answer

You need to get a handle to the DataTemplate itself and use its FindName method, referring to the parent control of your element.

For instance:

 var item = myItemsControl.ItemContainerGenerator.ContainerFromItem(xxx); var template = this.Resources["MyItemTemplate"] as DataTemplate; var ctl = template.FindName("textBox1", item) as FrameworkElement; 

Thus, in the element is a control called "textBox1".

If you do not use a named DataTemplate (that is, one with x: Key = "MyItemTemplate") and instead use DataType = "..." to determine the DataTemplate to be used for certain types, the method by which you modify the template a little :

 var actionKey = new DataTemplateKey(typeof(MyCustomClass)); var actionTemplate = Resources[actionKey] as DataTemplate; 
+5
source

Source: https://habr.com/ru/post/1301380/


All Articles