Search code examples
c#xamltelerikdatatemplatewindows-phone-8.1

Get the UserControl from DataTemplate


I have a DataTemplate in which i have simply used a UserControl.

DataTemplate x:Key="SampleDataTemplate">
        <controls1:UserControl1>

        </controls1:UserControl1>
</DataTemplate>

This DataTemplate is used in TransitionControl.ContentTemplate Now I want the UserControl1 Object in the c# CodeBehind.

Something Like this

TransitionControl.ContentTemplate this DataTemplate will give me UserControl1 object.


Solution

  • You could use VisualTreeHelper's GetChildrenCount and GetChild methods to get to the control that you need. Here's a method that will help (tweak it if necessary):

    private List<T> FindChildren<T>(DependencyObject startNode, List<T> results = null) where T : DependencyObject {
        if (results == null) results = new List<T>();
    
        int count = VisualTreeHelper.GetChildrenCount(startNode);
        for (int i = 0; i < count; i++) {
            DependencyObject current = VisualTreeHelper.GetChild(startNode, i);
            if ((current.GetType()).Equals(typeof(T)) || (current.GetType().GetTypeInfo().IsSubclassOf(typeof(T)))) {
                T realType = (T)current;
                results.Add(realType);
            }
            FindChildren<T>(current, results);
        }
    
        return results;
    }
    

    So, all you need to do is call FindChildren<UserControl1>(MyTransitionControlInstance) and you'll get get the instance of the UserControl1 control (well, all of the instances, if there are more).

    P.S. It really is a good idea to tweak the method to just look for one element, and not for all of them, if you need just one which seems to be the case.