tags:

views:

745

answers:

3

When I created a WPF UserControl and tried to use it, I got the following compiler error:

Because 'UserControl1' is implemented in the same assembly, you must set the x:Name attribute rather than the Name attribute.

The message is clear on what to do to fix it, but what is its cause? Why can't I use Name here?

A: 

Name must be unique within the assembly, you have another control/element with the same name.

You could rename it, use x:Name, or in some cases not provide a name at all.

Did you set the x:Class attribute?

Danny Varod
If you changed the name, you would still get the same error. Read the error message again. It has nothing to do with name collisions.
Joe White
A: 

Think of it like naming a variable; you can't have

var x = int;
var x = new DataTable();

within the same class. And that's what is happening when you try to provide the same name to two different elements in the same XAML file.

Same thing when you're creating classes, it's in essence

namespace y
{
public class z {}
public class z {}
}

which is not correct since they are not partial classes.

Elements must be atomic within their container.

MasterMax1313
But I don't have two different elements with the same Name attribute. It's just the one.
svick
+5  A: 

x:Name is simply a more explicit way of saying "The name attribute in this specific XML namespace". The fact that WPF can't compile it without being given this hint because it's in the same assembly is just a limitation of how they wrote the parser.

If you are asking why it is this way, I do not know for sure because I didn't write it. It probably has something to do with it needing to be able to resolve the Name attribute (read: Dependency Property) to something concrete BEFORE building your UserControl1, in other words, a catch-22.

slf