Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 912
user310291 Avatar asked Jan 24 '11 08:01

user310291


3 Answers

Instead of making button1, button2 etc, make a List of buttons.

Then you can write:

myList.ForEach( b => b.Click += button_Click );

From XAML you can attach the click handler to the parent of the buttons something like this (I use a StackPanel as an example):

<StackPanel Button.Click="button_Click">
  <Button .... >First button</Button>
  <Button .... >Second button</Button>
  <Button .... >Third button</Button>
</StackPanel>

This works because the buttons Click event is a bubbling routed event.

like image 21
Øyvind Bråthen Avatar answered Nov 19 '22 17:11

Øyvind Bråthen


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));
like image 169
Matt Hamilton Avatar answered Nov 19 '22 17:11

Matt Hamilton


You could use Linq To VisualTree to locate all the buttons in your Window / UserControl, then iterate over this list adding your event handler.

var buttons = this.Descendants<Button>().Cast<Button>();
foreach(var button in buttons)
{
  button.Click += button_Click;
}

I think that is about as concise as you are going to get it!

like image 1
ColinE Avatar answered Nov 19 '22 17:11

ColinE