Find a WPF element inside DataTemplate in the code-behind

Solution 1:

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  */
  }
}

Solution 2:

Do not do it. If you need to change something in a DataTemplate then bind the respective properties and modify the underlying data. Also i would recommend binding the Button.Command to an ICommand on your data/view-model (see MVVM) instead of using events, then you are in the right context already and the view does not need to do anything.