简体   繁体   中英

Getting name from sender(Multi Type) on WPF

Is it possible to have a event for all label,images,textblock,.... on wpf?

Label a=new Label();
a.name="object"+counter;
counter++;
a.MouseDown += _MouseDown;
grid.Children.Add(a);

Image b=new Image();
b.name="object"+counter;
counter++;
b.MouseDown += _MouseDown;
grid.Children.Add(b);

And event could be something like this: Instead of (Object) we are using one type (Image) or (Label)

void _MouseDown(object sender, MouseButtonEventArgs e)
{
     var scrollViewer = (Object)sender;  
      **and here I could get name of it**
}

So let me to know if it's possible to have all of them on one event please

Just cast it to a superclass that has the Name property. Actually, casting an object to Object is useless, they are the same thing and Object does not have a Name property.

 var scrollViewer = (FrameworkElement)sender; 

By simply looking up the MSDN documentation for Label and Image you find:

Name
Gets or sets the identifying name of the element. The name provides a reference so that code-behind, such as event handler code, can refer to a markup element after it is constructed during processing by a XAML processor.( Inherited from FrameworkElement .)

(Bold mine)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM