Mapping a Custom Property to x:Name
The more I get to know the System.Windows.Markup namespace, the more I like it. Here’s something I came across today when I implemented a method to walk through a collection and find an element by name. Because I was populating the collection using XAML, I wanted to name the elements in the collection using x:Name.
As you know, x:Name isn’t actually a property on the element where it gets set, but a “special” property in the x: namespace which can be set on any XAML element. In other words, even if a class doesn’t have a property called x:Name (or even just Name), you can still set x:Name on it.
Now x:Name is a useful thing to set because it does some cool things for you. The most interesting, of course, is that it gives you a variable with the same name that you can write code against.
Now on some elements there actually is a property called Name (notice no x: here). You’ve probably noticed that setting Name or setting x:Name generally seems to do the same thing. In other words, if I set plain old Name on an element, I still seem to get all of the magic of x:Name. Any FrameworkElement, for example, has a Name property that behaves like x:Name. This is very cool and I wanted to mimic this on the elements in my collection.
It turns out that doing this is very easy. All you need to do is define a property on your custom element (call it what you want, I’m not sure if there are constraints to the type though) and flag it as the “RuntimeNameProperty” using the RuntimeNameProperty class attribute. Like this:
[RuntimeNameProperty("Name")]
public class MyClass
{
private string _Name;
public string Name
{
get { return _Name; }
set { _Name = value; }
}
}
Once you do that, the magic just happens. Now, whenever I set the Name property on MyClass, I’ll automatically get all of the x:Name xamly goodness.
One Comment
Fabio Miguez / JUL 30 2007
Hi Rob,
Interesting, but I think I am not grasping the full impact this should have on me. Are you able to add x:Name to what, objects in your collection? I guess I am not quite sure of what a collection really is.
What I did get, though, is that you were setting x:Name in C#, not in XAML, right?
By the way, I just finished Chapter 6 of your TotalTraining WPF Essentials and am really happy with it. I have a couple of comments, could you shoot me an email?
Thanks,