How to: Find Control/DataTemplate-Generated Elements

http://msdn.microsoft.com/en-us/library/bb613586.aspx

http://msdn.microsoft.com/en-us/library/bb613579.aspx

To find an element within the template after the template has been applied, you can call the FindName method of the Template.

// Finding the grid that is generated by the ControlTemplate of the Button
Grid gridInTemplate = (Grid)myButton1.Template.FindName("grid", myButton1);

PS: for datatemplate, it is a bit tricky, because the datatemplate is actually applied on the contentpresenter. Therefore, you need first find the contentpresenter of the content control and call FindName on the ContentTemplate of the controlpresenter. Reference the second link above.
Advertisements

~ by Martin on October 8, 2008.

3 Responses to “How to: Find Control/DataTemplate-Generated Elements”

  1. Hi guys, I find a “clutter” way to find all controls within a ItemsControl’s DataTemplate:

    for (int i = 0; i < myItemsControl.Items.Count; i++)
    {
    ContentPresenter c = myItemsControl.ItemContainerGenerator.ContainerFromItem(myItemsControl.Items[i]) as ContentPresenter;

    DataTemplate myDataTemplate = c.ContentTemplate;
    YourControl yourControl = (YourControl)myDataTemplate.FindName("controlName", c);
    }

    I hope this helps everyone that was just like me, diggin'in google how to find controls inside a itemscontrol!

  2. Hola!!! trate de hacer lo que tu dices, pero me manda un null en c ??? por que hace eso

  3. No it doesn’t work with a DataGrid control.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: