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.

The
GetChildmethod will throw anArgumentOutOfRangeExceptionif the child with the given index does not exist. The exception message refers to theVisualChildrenCountproperty of theVisualthat you passed in. This property isprotectedas you have already noticed.However, you can use the
GetChildrenCountonVisualTreeHelperinstead. This method will access the aforementionedVisualChildrenCountproperty of the passed inVisualinternally.