Getting the name of an Element in Silverlight (WPF)

Quick post this, today I found myself wanting to get the name of element that raised an event, and as always the simpliest requests in Silverlight are often the hardest. Well ok, it wasn’t hard but perhaps not obvious so I thought I’d post it so at least I’ll be able to do it again…
 
So you put a click event on something and you want to know the name of the button…
<Button x:Name="Bob" />
 
Well the trick is knowing that name is a Framework Element property so…
 

private void Bob_Click(object sender, RoutedEventArgs e)

{

FrameworkElement frameworkElement = (FrameworkElement)sender;

string name = frameworkElement.Name;

}

Knowing that you could also use…

string name = ((UIElement)sender).GetValue(FrameworkElement.NameProperty).ToString();

…and knowing that you could e.OriginalSource depending upon the element you want to know the name of.

 

 

Advertisements
This entry was posted in Silverlight. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s