ArgumentOutOfRangeException when calling VisualTreeHelper.GetChild()

254 views Asked by At

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.

1

There are 1 answers

1
thatguy On BEST ANSWER

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.
   }
}