-1

From time to time I'm running into an ArgumentOutOfRangeException when calling VisualTreeHelper.GetChild().

The exception mentions not to call that method when VisualChildrenCount equals 0 - which is what the if right before the call supposedly does.

Am I missing something obvious here? I also tried to access contentPresenter.VisualChildrenCount but that property is protected.

Code with AregumentOutOfRangeException.

thatguy
  • 21,059
  • 6
  • 30
  • 40
  • Not sure why this is downvoted - the old code was obviously wrong but at the same time this is easy to misunderstand. The exception, after all, says "VisualChildrenCount" and not GetChildrenCount()... – Norbert Hüthmayr Dec 16 '20 at 19:35

1 Answers1

2

The GetChild method will throw an ArgumentOutOfRangeException if the child with the given index does not exist. The exception message refers to the VisualChildrenCount property of the Visual that you passed in. This property is protected as you have already noticed.

However, you can use the GetChildrenCount on VisualTreeHelper instead. This method will access the aforementioned VisualChildrenCount property of the passed in Visual internally.

if (VisualTreeHelper.GetChildrenCount(contentPresenter) > 0)
{
   if (VisualTreeHelper.GetChild(contentPresenter, 0) is UIElement contentVisual)
   {
      // ...your code.
   }
}
thatguy
  • 21,059
  • 6
  • 30
  • 40