How to get the RegisterName in WPF

rainnie1314 21 Reputation points

I dynamic create the button using code like this:

private void mainArea_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
targetPoint = e.GetPosition((IInputElement)sender);
Uid id = new Uid();
string uid = id.getUid();
_target = new Button()

                content = "station",

                Name = "station" + uid

            Canvas.SetTop(_target, targetPoint.Y - 60);
            Canvas.SetLeft(_target, targetPoint.X - 20);
            mainArea.RegisterName(_target.Name, _target);

And the "uid" is a random number, after this code i can create button on Canvas, but when i try to delete it or do something else , i found i cant get the name of the button.

so anyone can tell me how to get the name or registername of this button or the button that i click?

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,631 questions
0 comments No comments
{count} votes

Accepted answer
  1. DaisyTian-1203 11,611 Reputation points

    You can add _target.Click += _target_Click; in your mainArea_PreviewMouseLeftButtonDown event and add below code for _target_Click

     private void _target_Click(object sender, RoutedEventArgs e)  
                Button btn = sender as Button;  

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful