Cant get a control from a TabControl DataTemplate <p>I've been googling this for the last 2 days and cant get anywhere, I just cant do anything to any control in a datatemplate of a tabcontrol. </p> <p>First off, the code:</p> <pre><code>private void Window_Loaded(object sender, RoutedEventArgs e) { tabControl1.ItemsSource = new string[] { "TabA", "TabB", "TabC" }; } private void tabControl1_SelectionChanged(object sender, SelectionChangedEventArgs e) { ContentPresenter cp = tabControl1.Template.FindName("PART_SelectedContentHost", tabControl1) as ContentPresenter; DataTemplate dt = tabControl1.ContentTemplate; Grid g = tabControl1.ContentTemplate.FindName("myGrid", cp) as Grid; g.Background = new SolidColorBrush(Colors.Red); } </code></pre> <p>xaml</p> <pre><code>&lt;Window x:Class="tabTest.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded"&gt; &lt;Grid&gt; &lt;TabControl IsSynchronizedWithCurrentItem="True" Height="140" Name="tabControl1" Width="230" SelectionChanged="tabControl1_SelectionChanged"&gt; &lt;TabControl.ContentTemplate&gt; &lt;DataTemplate&gt; &lt;Grid x:Name="myGrid"&gt; &lt;/Grid&gt; &lt;/DataTemplate&gt; &lt;/TabControl.ContentTemplate&gt; &lt;/TabControl&gt; &lt;/Grid&gt; </code></pre> <p></p> <p>In short this line:</p> <pre><code>Grid g = tabControl1.ContentTemplate.FindName("myGrid", cp) as Grid; </code></pre> <p>throws an error "System.InvalidOperationException" This operation is valid only on elements that have this template applied.</p> <p>this particular idea i got from <a href="http://www.netframeworkdev.com/windows-presentation-foundation-wpf/accessing-elements-inside-a-datatemplate-27994.shtml" rel="nofollow">here</a></p> <p>I've found loads of other ways of doing this but I cant seem to get anywhere :( hope someone can point me in the right direction :)</p>