开发者

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 i开发者_如何转开发n 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 could use the Tag for that, needs to be cast when getting the object though.


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.


you can also inherit Button and put your class over there...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜