How can I retrieve the DataTemplate (and specific objects) of an item in an ItemsControl?

有些话、适合烂在心里 提交于 2019-12-05 13:33:59

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

For example:

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

So this finds a control called "textBox1" inside the item.

If you're not using a named DataTemplate (ie one with x:Key="MyItemTemplate") and instead using DataType="..." to define a DataTemplate to be used for specific types, the method by which you find the template changes slightly:

var actionKey = new DataTemplateKey(typeof(MyCustomClass));
var actionTemplate = Resources[actionKey] as DataTemplate;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!