Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add parameter to Button click event

I have a wpf button like this:

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

And I want to pass {Binding Code} passed as parameter to the button1_click handler.
How do I go about this?

Disclaimer: really new to WPF

like image 592
Boris Callens Avatar asked Jan 05 '10 14:01

Boris Callens


2 Answers

Simple solution:

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

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

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

A more elegant solution would be to use the Command pattern of WPF: Create a Command for the functionality you want the button to perform, bind the Command to the Button's Command property and bind the CommandParameter to your value.

like image 83
Heinzi Avatar answered Sep 21 '22 07:09

Heinzi


I'm not overly a fan of 'Tag' so perhaps

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

Then accessing via the Attributes.

 void button1_Click(object sender, RoutedEventArgs e)  {     var button = sender as Button;     var theValue = button.Attributes["myParam"].ToString()  } 
like image 31
TheMonkeyMan Avatar answered Sep 21 '22 07:09

TheMonkeyMan