How do I programatically interact with template generated elements?

Platform: WPF| Category: Templates

Getting hold of an element in a ControlTemplate is very easy, as this article explains:

How do I programmatically interact with template-generated elements? Part I

Sample code:


Grid gridInTemplate = (Grid)myButton1.Template.FindName('grid', myButton1);

But, if want to get hold of an item in a DataTemplate (which gets applied for each item in the ItemsControl), then there is more code involved as explained here:

How do I programmatically interact with template-generated elements? Part II

Sample Code:


// Note that the ListBox must have
// IsSynchronizedWithCurrentItem set to True for this to work
ListBoxItem myListBoxItem = (ListBoxItem)(myListBox.ItemContainerGenerator.ContainerFromItem(myListBox.Items.CurrentItem));
ContentPresenter myContentPresenter = FindVisualChild(myListBoxItem);
DataTemplate myDataTemplate = myContentPresenter.ContentTemplate;
TextBlock myTextBlock = (TextBlock)myDataTemplate.FindName('textBlock', myContentPresenter);

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.