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

后端 未结 3 1394
死守一世寂寞
死守一世寂寞 2020-12-10 18:56

I have multiple buttons instead of doing

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


        
3条回答
  •  一生所求
    2020-12-10 19:29

    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):

    
      
      
      
    
    

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

提交回复
热议问题