Ini...">

Add Parameter to Click Button Event

I have a wpf button:

<Button Click="button1_Click" Height="23" Margin="0,0,5,0" Name="button1" Width="75">Initiate</Button> 

And I want to pass the {Binding Code} passed as a parameter to the button1_click handler.
How should I do it?

Disclaimer: Really New for WPF

+42
c # button click wpf
Jan 05 '10 at 14:12
source share
3 answers

A simple solution:

 <Button Tag="{Binding Code}" ...> 

In your handler, add the sender object to the Button and access the Tag property:

 var myValue = ((Button)sender).Tag; 



A more elegant solution would be to use the WPF Command Template : create a command for the function you want the button to execute, bind Command to the Button Command property and bind CommandParameter to your value.

+83
Jan 05 '10 at 14:18
source share

I'm not a big fan of the tag, so maybe

 <Button Click="button1_Click" myParam="parameter1" Height="23" Margin="0,0,5,0" Name="button1" Width="75">Initiate</Button> 

Then access through the attributes.

  void button1_Click(object sender, RoutedEventArgs e) { var button = sender as Button; var theValue = button.Attributes["myParam"].ToString() } 
+13
Sep 28 '12 at 9:44
source share

Well, there are two ways to do this:

Insert DataContext

  void button1_Click(object sender, RoutedEventArgs e) { var button = sender as Button; var code = ((Coupon)button.DataContext).Code; } 

Or use the Tag property, which is a common state property

  <Button Click="button1_Click" Height="23" Margin="0,0,5,0" Name="button1" Tag="{Binding Code}" /> 

then

 void button1_Click(object sender, RoutedEventArgs e) { var button = sender as Button; var code = button.Tag; } 
+6
Jan 05 '10 at 14:19
source share



All Articles