Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 293
TDaver Avatar asked Mar 04 '11 11:03

TDaver


3 Answers

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); }
}
like image 59
ChuckEng Avatar answered Nov 12 '22 01:11

ChuckEng


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.

like image 29
AnthonyWJones Avatar answered Nov 12 '22 02:11

AnthonyWJones


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);
    }
}
like image 38
Alex Burtsev Avatar answered Nov 12 '22 01:11

Alex Burtsev