Silverlight: Cannot specify both Name and x:Name attributes

I received the following error while upgrading from Silverlight beta 1 to beta 2: Cannot specify both Name and x:Name attributes. I’m sure there can be many causes, but since there isn’t much written on this, here is one cause.

If you have a custom control you can no longer put an x:Name on the root element if you also have an x:Name on an instance of the control. A crappy work-around is to declare the root node in code and set it to the parent of a child element. For instance:

<Canvas x:Class="MyNamespace.MyCustomControl"
    xmlns="http://schemas.microsoft.com/client/2007"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Name="LayoutRoot"
    >
    <StackPanel x:Name="_stackPanel">

Canvas LayoutRoot;

/// <summary>
///
Constructor
/// </summary>
public MyCustomControl() {
    InitializeComponent();

   // set _controlBase after InitializeComponent
   //     so _stackPanel is initialized
   LayoutRoot = (Canvas)_stackPanel.Parent;
}

This is pretty fragile, so I’d love to hear any other solutions.

Comments