Getting controls from inside a DataTemplate
October 19, 2010 Leave a comment
Today I had to access a control which resided inside a DataTemplate used by a PivotItem (WP7) and there’s no straight forward way to do this as far as I know.
Thing is that pivotControl.Items[idx] returns the databound item and pivotControl.ItemContainerGenerator.ContainerFromItem(item) yields a PivotItem. But I figured that pivotItem.Content would contain the controls defined in the DataTemplate – wrong, it gives back the databound item.
So, my next try was to use the pivotItem.ContentTemplate.LoadContent() which actually did give me my controls – but LoadContent() actually creates a new object and doesn’t give you the reference to the actual live object on your screen.
Of course, the solution is rather simple if you can just think of it right off the bat![]()
First, get the container:
DependencyObject container = pivotControl.ItemContainerGenerator.ContainerFromItem(item);
Then we use the VisualTreeHelper to take a walk around and find the control we want (by name).
var details = container.GetChild<Detail>("details");
This is all possible with this little extension method:
public static T GetChild<T>(this DependencyObject parent, string name) where T:DependencyObject{ for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++) { DependencyObject child = VisualTreeHelper.GetChild(parent, i); if (child.GetType() == typeof(T) && ((FrameworkElement)child).Name == name) return (T)child; if (child.GetChild<T>(name) != null) return child.GetChild<T>(name); } return null; }
If there’s a simpler solution to this, please let me know![]()