Why does the SelectTemplate method run 2 times in debug mode?

Debugging this class using the SelectTemplate method is done 2 times, but why?

The first time the item is always zero.

public class PersonDataTemplateSelector : DataTemplateSelector
{
    public override DataTemplate SelectTemplate(object item,DependencyObject container)
    {
        if (item is Person)
        {
            Person person = item as Person;

            Window window = Application.Current.MainWindow;

            if (System.ComponentModel.DesignerProperties.GetIsInDesignMode( window))
                return null;

            if (person.Gender == "male")               
                return window.FindResource("boysViewTemplate") as DataTemplate;
            else                
                return window.FindResource("girlsViewTemplate") as DataTemplate;

        }
        return null;
    }
}
0
source share
2 answers

You can set a breakpoint and check the stack trace to check, but I believe that it called once with zero input when the visual tree is configured, and the second time when the bindings are actually bound.

0
source

If your selector was to search for "Empty" or "Loading", the first call is what gives your selector the opportunity to provide this template when loading items.

0

All Articles