Is it possible to get x:Name of a DependencyObject (Silverlight)?
Asked Answered
S

3

6

I have a DependencyObject (an Interactivity Behavior), and I'd like to get its x:Name (just get, not set) from code. Is it possible?

EDIT: Following AnthonyWJones's answer:

I've inserted the following code into my base behavior:

[EditorBrowsable(EditorBrowsableState.Never)]
public string Name
{
    get { return (string)GetValue(NameProperty); }
    set { SetValue(NameProperty, value); }
}

public static readonly DependencyProperty NameProperty =
            DependencyProperty.Register("Name", typeof(string), typeof(BaseBehavior<T>), new PropertyMetadata(null));

I've given my behaviors x:Name, yet the Name property doesn't get filled.

Searle answered 4/3, 2011 at 11:29 Comment(0)
A
4

If you want your Name property to be the same as the x:Name XAML name, then instead of implementing your own dependcy property, piggy-back on the existing one that is already registered. You can simply implement your name property as:

public string Name
{
    get { return (string) base.GetValue(FrameworkElement.NameProperty); }
    set { base.SetValue(FrameworkElement.NameProperty, value); }
}
Amund answered 1/5, 2011 at 8:44 Comment(0)
I
2

If the class deriving from DependencyObject does not expose a Name property then you cannot determine the assigned x:Name. The x:Name value is store only in an internal object tree and there is no API to resolve value (the object) back to a key value (the name).

However if this is your own behaviour then simply add a Name dependency property to your behaviour. x:Name will assign is value to a Name property if present.

If this an existing behaviour you may be able to inherit from it to create a new class that has a Name property. Unfortunately some behaviours are sealed so you can't always do this.

Isostasy answered 4/3, 2011 at 17:0 Comment(3)
@AnthonyWJones: so, do you have any idea WHY it is not working?Searle
@TDaver: That's quite strange, try just Name instead of x:Name.Isostasy
if I set Name from xaml, it works, if I set x:Name it doesnt (and by doesn't, I mean the DependencyProperty NameProperty doesn't get set)Searle
T
2

You can create 'Name' AttachedProperty, and use NameAttachedProperty.GetName(DependencyObject)

Of course you will have to attach it to your element before using.

public static class NameAttachedProprty
{
    public static readonly DependencyProperty NameProperty =
        DependencyProperty.RegisterAttached("Name", typeof (string), typeof (NameAttachedProprty), new PropertyMetadata(default(string)));

    public static void SetName(DependencyObject element, string value)
    {
        element.SetValue(NameProperty, value);
    }

    public static string GetName(DependencyObject element)
    {
        return (string) element.GetValue(NameProperty);
    }
}
Tabasco answered 23/11, 2011 at 8:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.