In WPF, can I attach the same click handler to multiple buttons at the same time, how can I in Javascript / JQuery?

I have some 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 would like to do something like this in pseudocode:

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

Is something similar possible in javascript in WPF?

+5
source share
3 answers

In WPF, it Button.Clickis a routable event , which means that the event is routed up the visual tree before it is processed. This means that you can add an event handler to your XAML, for example:

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

Now all buttons will share one handler (button_Click) for their Click event.

, . , AddHandler, :

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

. , StackPanel (, "stackPanel1" ) :

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

button1, button2 .. .

:

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

XAML ( StackPanel):

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

, Click event - .

+3

Linq To VisualTree, Window/UserControl, , .

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

, , !

+1

All Articles