Tip: Don’t be scared to use x:Name in XAML
February 17, 2009 @ 1:30 pm in Industry, Silverlight
Yesterday I was working on some Silverlight production and needed to create a custom UserControl that had some text. The trick was that I wanted the user placing the control to choose which color the text would be, inturn effecting the second key frame on a simple ColorAnimationUsingKeyFrames
My animation was really simple, I wanted the text to start out as white old for a few milliseconds then fade into my dynamic color. My first tendency was to just create the Storyboard procedurally, but did not want to lose the “blendability” of my control. Then it dawned on me how simple the solution was. Just name the second KeyFrame.
All to often we forget that we can give virtually any XAML node an x:Name and the framework will create a private reference to the element.
<SplineColorKeyFrame x:Name="destColor" KeyTime="00:00:00.3000000"
Value="{StaticResource GemColor}"/>
Once we have named our node, in the corresponding code behind we can simply reference any property from that element.
destColor.Value = Color.FromArgb(255, 10, 10, 10);
/p>
Tagged as 

February 17th, 2009 at 8:13 pm
Here here. I believe x:Name should be specified for all elements. It forces you to make sure each element has a purpose. Sure, sometimes it’s a pain but once you’re use to it you won’t regret it.
February 18th, 2009 at 8:59 am
I think you have to be selective since it is creating a private references for each named element. I have seen complex user controls, such as vector sprites in a game with tons of named path’s, that have thousands of references on the stack. If your not going to need it in code behind then you don’t need to give it a x:Name.
February 18th, 2009 at 12:42 pm
This is an excellent suggestion! I have often wanted to have dynamic keyframe values!