Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I store an Object inside a button in C#

I am creating Buttons dynamically in my code, is there a way I can store a custom object in my button so I can use it when I press this button ?

like image 384
raym0nd Avatar asked Jul 25 '11 20:07

raym0nd


3 Answers

Consider using the command pattern and bind a command to the button's Command property and use the CommandParameter Property to store your object.

When the button is clicked the Execute method of your command will be invoked using the CommandParameter (containing your object) as parameter.

It would be good to know the scenario you are working at. Generating XAML by code is a sign you may be on the wrong track as long as you are not building custom controls.

Most things can be accomplished via data bindings and repeater controls such as listboxes, menus, datagrids, etc. Are you familar with the MVVM pattern?

like image 110
Zebi Avatar answered Nov 16 '22 12:11

Zebi


You also could use an attached property.

like image 30
H.B. Avatar answered Nov 16 '22 14:11

H.B.


There are tons of options to do that declaratively (through binding to Tag or other non-used fields) or not, but one less intrusive way if you are creating buttons dynamically would be to simply create a Dictionary<Button, T> mapping which stores needed object for each button.

like image 1
Grozz Avatar answered Nov 16 '22 13:11

Grozz