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 ?
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?
You also could use an attached property.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With