Tip: Don’t be scared to use x:Name in XAML

Date 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}"/>

tip1

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>

3 Responses to “Tip: Don’t be scared to use x:Name in XAML”

  1. Corey Schuman said:

    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.

  2. joel said:

    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.

  3. Jeremy said:

    This is an excellent suggestion! I have often wanted to have dynamic keyframe values!

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">