Find a WPF element inside DataTemplate in the code-behind

Robert Langdon picture Robert Langdon · Aug 6, 2012 · Viewed 30k times · Source

I have a data-template

<Window.Resources>
         <DataTemplate x:Key="BarChartItemsTemplate">
         <Border Width="385" Height="50">
            <Grid>
               <Rectangle Name="rectangleBarChart" Fill="MediumOrchid" StrokeThickness="2" Height="40" Width="{Binding}" HorizontalAlignment="Right" VerticalAlignment="Bottom">
                  <Rectangle.LayoutTransform>
                     <ScaleTransform ScaleX="4"/>
                  </Rectangle.LayoutTransform>
               </Rectangle>
               <TextBlock Margin="14" FontWeight="Bold" HorizontalAlignment="Right" VerticalAlignment="Center" Text="{Binding}">
                  <TextBlock.LayoutTransform>
                     <TransformGroup>
                        <RotateTransform Angle="90"/>
                        <ScaleTransform ScaleX="-1" ScaleY="1"/>
                     </TransformGroup>
                  </TextBlock.LayoutTransform>
               </TextBlock>
            </Grid>
         </Border>
      </DataTemplate>
  </Window.Resources>

I have a button on the form. I need to change the scale(scaleTransform) the rectangle from the dataTemplate. How am I supposed to access the 'rectangleBarChart' element in the Button_Click event of the above mentioned button ?

Answer

Mark Oreta picture Mark Oreta · Aug 6, 2012

I use this function a lot in my WPF programs to find children elements:

public IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
   if (depObj != null)
   {
       for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
       {
           DependencyObject child = VisualTreeHelper.GetChild(depObj, i);

           if (child != null && child is T)
               yield return (T)child;

           foreach (T childOfChild in FindVisualChildren<T>(child))
               yield return childOfChild;
       }
   }
}

Usage:

foreach (var rectangle in FindVisualChildren<Rectangle>(this))
{
  if (rectangle.Name == "rectangleBarChart")
  {
    /*   Your code here  */
  }
}