Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
816 views
in Technique[技术] by (71.8m points)

wpf controls - In WPF can I attach the same click handler to multiple buttons at once like I can in Javascript/Jquery?

I have multiple buttons instead of doing

this.button1.Click += new System.EventHandler(this.button_Click);
this.button2.Click += new System.EventHandler(this.button_Click);
etc.
this.button10.Click += new System.EventHandler(this.button_Click);

I'd like to be able to do something like this in pseudo-code:

this.button*.Click += new System.EventHandler(this.button_Click);

In Javascript it is possible is there something like that in WPF ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In WPF, Button.Click is a routed event, which means that the event is routed up the visual tree until it's handled. That means you can add an event handler in your XAML, like this:

<StackPanel Button.Click="button_Click">
    <Button>Button 1</Button>
    <Button>Button 2</Button>
    <Button>Button 3</Button>
    <Button>Button 4</Button>
</StackPanel>

Now all the buttons will share a single handler (button_Click) for their Click event.

That's an easy way to handle the same event across a group of controls that live in the same parent container. If you want to do the same thing from code, you can use the AddHandler method, like this:

AddHandler(Button.ClickEvent, new RoutedEventHandler( button_Click));

That'll add a handler for every button click in the window. You might want to give your StackPanel a name (like, "stackPanel1") and do it just for that container:

stackPanel1.AddHandler(Button.ClickEvent, new RoutedEventHandler( button_Click));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...