Welcome to Pete Brown's 10rem.net

First time here? If you are a developer or are interested in Microsoft tools and technology, please consider subscribing to the latest posts.

You may also be interested in my blog archives, the articles section, or some of my lab projects such as the C64 emulator written in Silverlight.

(hide this)

Silverlight/WPF: Don't name elements unless you have to: why x:Naming everything is bad

Pete Brown - 02 July 2010

By Quinn Dombrowski http://www.flickr.com/photos/quinnanya/4464205726/

XAML, much like HTML, doesn't require naming every element in the markup. This is a *ahem* marked difference from the client app dev technologies we've had in the past, like Windows Forms and various forms of VB. In fact, just about every client-side app dev technology, except maybe dialog resources in Win32, has required that I provide a name for every on-screen element that is backed up by a class of some sort.

The net result is you often end up with a namespace polluted with Label1, Label2, Label3 etch. Those are completely meaningless names, and show they're being named only because the tool/platform/language requires it.

I remember back in the day, the "Label1" look was so offensive to some, that they'd go and name every single label, group, line and more on the form even if they never referred to them in code. What an incredible waste of time for a developer.

Naming in HTML

When I'm working in HTML I don't give an id to every paragraph element, li, and span on the page. While you can, and it can even be useful in some styling scenarios, it strikes me as a lot of extra work. I do usually name divs, as I'm far more likely to refer to them in a style or hunk of jQuery code. I like that HTML, and the tools we use, give me an option here.

I follow a similar model when working in XAML.

Naming in XAML

When working in XAML, I follow the "don't name it until you have to" philosophy for most elements. XAML is much like HTML in that you don't need to name everything.

Naming an element on a UserControl-derived bit of XAML markup creates a variable in the code-behind. Each one of those variables takes up precious byte space in the compiled application. Each one takes up a very small but real amount of time in the InitializeComponent call. Each one adds more chaff to the intellisense list. Each one creates a member variable which can be referred to from outside your class, breaking encapsulation.

I know some of the templates, and the designer, don't follow this approach. I've put requests in to the teams, so I'm optimistic that these will be changed in the future. Normally I don't fight the IDE or templates, as those end up becoming standards. In this case, however, I know lots of folks who agree with me.

Naming everything in XAML can lead to future maintenance problems. For one, it makes it harder to know what elements you're actually referring to in storyboards or code-behind. If you're working with a designer, they don't know at a glance which elements they can safely remove when trying out a new design.

Elements I normally Name in XAML

Interactive UI controls like TextBoxes, ListBoxes, Buttons etc. You can get away without naming these if you're using commands/behaviors and a good pattern like MVVM, but I find naming is helpful from a documentation standpoint. Not a requirement by any means, but helpful.

Sometimes I'll provide an x:Name to a render transform inside an element if I wish to use it in a storyboard. I find this (in most cases) much nicer than using the dot-down syntax favored by Blend. Both work, of course.

Anything which serves as part of a designer/developer contract gets a name. Avoiding naming everything else makes it much more clear which elements are part of that contract.

Elements I normally do not Name

I usually don't name chrome elements: borders, lines, rectangles and similar. I almost never name labels/TextBlock instances

With the exceptions in the previous section in mind, I never name anything that won't be referred to in code or by other elements. If you later decide you need to refer to them, it's really easy to add the name in, indicating a contract that must now be adhered to.

Summary

In WPF and Silverlight, avoid naming elements which aren't referred to elsewhere (code, animation, element binding). Adding a name to the element helps indicate a dependency and serves as a little bit of self-documentation. Adding a name to an element which isn't referred to simply adds to confusion.

(nametag picture by Quinn Dombrowski)

Related
         
posted by Pete Brown on Friday, July 2, 2010
filed under:          

24 comments for “Silverlight/WPF: Don't name elements unless you have to: why x:Naming everything is bad”

  1. Andrew Chisholmsays:
    I agree for the most part about not naming everything, except sometimes it can be useful knowing (especially when Snooping etc.) that a Grid is a HeadingPanel etc. Even if it has no behavior it can simplify finding thins. I suppose this could also be considered part of a "Developer/Designer" contract.
  2. Alan Mendelevichsays:
    While from programmers perspective this is reasonable I guess designers want to see some meaningful names in their object trees in Blend so it's easier for them to navigate their elaborate templates. There must be some way to add some d:Name or something. Or is there?
  3. Shane Morrissays:
    As a designer, I always name, at least, the major containers (grids, stackpanels etc) so that I can, as Alan suggests, find my way around the tree.

    In HTML it is easier to identify div's etc without names because:
    1. The content is right there and visible.
    2. The order of the HTML is more likely to reflect the relative position on the page
    3. The style tags are visible, and they're a good hint.

    Shane
  4. Briansays:
    Ah, a story of actors and props.

    Actors with big x:names like to play, take on behaviors, and become animated. Props prefer to go id-less and not play around and blend into the scene.. Of course a story needs a stage, perhaps made of grid, stacked panels or a canvas or two. In a more complex scene, it may be help to name a few key layout props to provide markers for the actors to find their queue. Places everyone, ready for the main event. Take four!

    Brian
  5. Yasser Mohamedsays:
    I agree with you about not naming everything and actually iam using MVVM so i almost never name elements after i went through your post i'll go through my App and remove X:Name for Elements coz of reasons you mentioned
    thx alot
    Best regards
    Yasser
  6. dennysays:
    I do not know if this can happen in WPF but in silverlight at times you *MUST* assign names.

    the dreaded error that says the control is already in the tree and you can't add the new one.
    i do not recall the proper name right now for that but it has to do with adding and removing controlls at runtime and not having all of them named so that the system can tell which one we are refering to in the tree.
  7. Bigsbysays:
    I'm with you, Pete.

    It's totally meaningless to name silent UI elements: If your Visual Tree was only 3 UIElements e doesn't make much diferent but I'm on the never thing little side on these things. When your VisualTree starts to get bigger and deeper, you start feeling the pain of the little meaningless oversights.

    It's just like using curly brackets ('{ }') to wrap single instructions in 'if' or, worst, in loops ('for', 'while', 'do' / 'while', etc.) . Some might say it looks nicer, and tools like StyleCop request it, but the fact is that a meaningless and very consuming variable scope is created.
  8. Atul Guptasays:
    I don’t completely buy this argument and why only talk about x:Name? When you use Blend, there are many instances when additional properties are added to XAML like margins, gradients, column widths and transforms. Why won’t these cause additional bytes, additional processing time, so why single out x:Name only?
  9. Petesays:
    @Atul

    In many cases, they do add additional bytes, but they're not adding code, they're not implying a contract between code and markup, and they're not adding to the public interface of the class. Margins, gradients and whatnot all provide real value. Not sure why you'd compare those with x:Name with things that don't need to be named.

    Using x:Name causes a member variable to be generated in the code-behind, as well as a call to FindName to be added to the IniitalizeComponent call. The former is why you see the members in intellisense, and why they show up as properties of the class. The latter is why they are not-null at runtime.

    Not asking you to "buy" anything :)

    Pete
  10. Dave Arkellsays:
    Good idea about the dev/designer contract thing. I hadn't really thought of that before (because we don't have a designer probably), but it makes sense.
  11. SpamMesays:
    I feel the same way, I don't like to waste time to name an element, which I don't need to manipulate from the code behind. But do you have ever taken a look to the silverlight controls xaml?
    Almost every element inside the control template has a name, of course it is needed for the visual states and for the storyboard.
    But at this point I'm wondering what difference does one more name on a control, which has already 20 or more named elements.
  12. Petesays:
    @SpamMe

    The issue of extra items generated in code is an annoyance, but won't result in much of a real burden. For me, the biggest issue is the implied contract. If you name something in XAML, I'm going to assume it's because you're referring to it in binding, a storyboard, or code-behind.

    Recklessly naming everything can tie the hands of a designer (or maintainer) and make the contract unclear.

    Pete
  13. Michael Syncsays:
    If I remember correctly, the auto id (automationid) will be generated for un-named controls. When you re-compile and run it again then there is a chance that id will be different. ( The id will be the same for the most of the time but I got a few reports about diff id. ) So, if you are using UI automation script for UI testing, it's better to give the name..
  14. Guy Hurstsays:
    You didn't mention concern for Section 508 and support for relevant assistive technologies that use the UI Automation API,
    I'd like to see a followup by you addressing how this might change your approach to x:Name.

    For example, our current project must support Section 508, including assistive technologies such as the JAWS reader. I have discovered a couple of things leading me to believe that it is important (or at least useful) to name many elements that otherwise would not be needed for coding or designers.
    1) For AutomationProperties.LabeledBy support, you will need to x:Name your Label controls.
    2) MSDN documentation states that AutomationId will use the assigned Name by default:
    "The Name property also serves as an identifier for other processes. For instance, the WPF automation model will use Name as the AutomationId for clients and providers."
    (http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.name.aspx)

    @Michael Sync: I don't think we can rely on auto-generated AutomationId values without setting the Name if you are correct about them changing. MSDN docs state:
    "When it is available the AutomationIdProperty of an element is expected to always be the same".
    (http://msdn.microsoft.com/en-us/library/system.windows.automation.automationelement.automationidproperty.aspx)
  15. RJ Sampsays:
    Agree totally, but my boss doesn't and unfortunately it's his way or the highway....and you 'may' need to refer to a control sometime in the future....something you can't even remotely fathom in 2011....it's better for documentation and documentation automation......

    and how much time are we talking here? a few minutes of time per form whilst you sip coffee and collect your thoughts? Less time than posting up here how we're {lazy} and want to whine about something?

    I remember initializing all variables in FORTRAN back in the day.....we complained about it mightily but it certainly pinpointed issues when the Octal core dump came back from an abort....7777777777 (yep, 80 bit octal machines).

    I'd say Cowboy Up, grow some, suck it up, and quit the complaining.
  16. Benny Pedersensays:
    I know, this thread started long ago, but I stumbled across it in search for answers about, when to ID controls.
    I Wonder, how you will foresee, which controls will be necessary to give an ID. Both automated testing tools and tools for accessibility for disabled heavily depend on the precise identification of controls, so from what you Guys write, you don't care about testing and disabled.

Comment on this Post

Remember me