简体   繁体   中英

Pass name of button to click event

I am generating a number of buttons with similar or identical content and was hoping to use the names they are given to differentiate them. As the program is creating the buttons dynamically I can't create a separate event for them all and instead need to be able to grab the name to be able to know which button triggered the event.

Is there a way to pass through the name of a button to the click event it initiates? the sender object seems to contain the content but not the name.

It is for a event like this:

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        //getname of button
        Canvas.Children.Remove(//name of button\\)
    }

Far as I know, WPF does not even assign anything to the Name property automatically - that's just for developers to assign so we can reference the control.

However, you should be able to just pass in the sender to the remove method since it accepts a UIElement argument which Button is derived from.

Canvas.Children.Remove((Button)sender);

I'm not familiar with WPF. If this answer appears to be a junk, I'll delete it.

In ASP.Net, we can cast to a button to get the sender's information. Something like this -

private void Button_Click(object sender, RoutedEventArgs e)
{
    var button = sender as Button;
    button.Name
}

Perhaps getting at the control's name will work for you

private void button1_Click(object sender, RoutedEventArgs e)
{
  Control control = (Control)sender;
  Canvas.Children.Remove(control.Name);
}

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