It was the hat that did it.
Having been allowed to choose from Theoden's stock of horses, Gandalf had made his way to the stable and grazing grounds. Having inspected the one called Shadowfax, Gandalf moved on to examine a mare, knowing them to be of gentler tempers.
He knelt to examine her leg when his hat was snatched off his head. Standing, he whirled to find it within the reach of Shadowfax. Reaching for the hat, Gandalf watched the animal dance backwards, holding his hat high in the air. Clutching his staff, the Wizard muttered under his breath. It was a spell meant to calm animals and make them more tractable. He didn't often use it, but his hat was at stake.
The horse, that damnable, arrogant stallion LAUGHED at him. Though his teeth were closed around Gandalf's hat, the horse was clearly laughing at him. Scowling, Gandalf glanced at his eyes and saw a frightening intelligence laughing back at him. He realized Shadowfax was no mere horse. He was something else - descended from creatures so old, they no longer walked the earth in pure form, having bred too oft with lesser creatures such as horses and the like. Slowly, he reached to stroke Shadowfax's neck, still drawn into those liquid brown eyes.
Shadowfax seemed to nod, setting Gandalf's hat back atop his head, only to knock it off again when he pressed his muzzle against the wizard's neck. Laughing, Gandalf ignored his hat as he wrapped his arms around the strong neck of the stallion, leaning against his strong body. He knew in that moment that Shadowfax was his and no other's, whoever else might lay claim to him. "Come, friend," he spoke in an ancient language that even Elves had forgotten. "We shall have fine adventures."
Nuzzling the wizard once more, Shadowfax bowed his great neck and delicately picked up Gandalf's hat by the point. Gently, in the manner of putting a flower into a lover's hair, he set the hat back atop the wizard's head.