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.
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); }
}
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.
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With