Accessing Properties and Objects in Silverlight Datatemplates using Loaded and FindName

Accessing properties and objects in a DataTemplate is not as easy as you would think. Normally the Template is separated from the item that uses it. You can find the DataTemplate as a Resource, but you cannot use the VisualTreehelper on it.

DataTemplate dt = Application.Current.Resources[“TheDataTemplate”] as DataTemplate;
int count = VisualTreeHelper.GetChildrenCount(dt);

This leads to the error: Reference is not a valid visual DependencyObject.

The solution is to use the Loaded event of the outermost container, quite often a Grid and use FindName in the EventHandler to get to Objects inside the DataTemplate and to properties of those:

<DataTemplate x:Key=”TheDataTemplate”>
    <Grid x:Name=”TheGrid” Grid.Row=”0″ Loaded=”TheGrid_Loaded”>
        //Objects and properties are here…
    </Grid>
</DataTemplate>

//enabling buttons in DataTemplate when Oob en Elevated…
private void TheGrid_Loaded(object sender, RoutedEventArgs e)
{
    if (Application.Current.IsRunningOutOfBrowser)
    {
        if (Application.Current.HasElevatedPermissions)
        {
            Grid grd = sender as Grid;

            if (grd != null)
            {
                Button c = grd.FindName(“btnCall”) as Button;
                c.IsEnabled = true;
                Button m = grd.FindName(“btnMail”) as Button;
                m.IsEnabled = true;
                Button p = grd.FindName(“btnCopy”) as Button;
                p.IsEnabled = true;
                Button v = grd.FindName(“btnVCard”) as Button;
                v.IsEnabled = true;

            }
        }
    }
}

Hope this helps! Njoy!