As my program grows and grows, I've been finding I'm using Control.Tag
more and more. I'm not really sure why Microsoft put it there, but I find it quite useful.
I'm left wondering: What was their original purpose? What is considered acceptable and what is considered taboo?
According to MSDN, Control.Tag
"Gets or sets the object that contains data about the control."
In my calendar application, I store the actual Appointment
object which an AppointmentControl
represents. I suspect this is the intended use of it and the example on MSDN would seem to confirm this, however I also do some more unusual things.
For example, when I have a back/next pair of buttons and I want back to be disabled when we reach the start, and next to be disabled when we reach the end, then I store the next button in the Tag of the previous, and the previous button in the Tag of the next. That way, I can always set the ((Button)Tag).Enabled = true
on click (Because when you move back, clearly a disabled next button will become enabled, and vice-versa).
Also, my calendar is made up of a (visually) two-dimensional array of Panels. I store the DateTime
which each panel corresponds to in the Panel.T开发者_开发知识库ag
, and when the user zooms in to see the time slots in a day, the Panels which make up each timeslot has a TimeSpan in their Tag which represents the start time of the slot.
So I'm curious: What do you think is the most common use of Tag? What is a more unusual application of Tag you have used or seen? Would you consider storing a linked object (as in my back/next button example) to be "hacky"?
Some people oppose the use of Tags, suggesting that they are remnants of older languages. A common complaint is that it is better to simply extend a control so that it contains a strongly-typed object rather than something arbitrary which needs to be cast when used. What do you think about it?
This came from VB6, its controls had a Tag property as well. It is a very poor substitute for a field in your class, it isn't type safe since Tag is of type Object. Makes your code hard to read too, it has a non-specific name. If you need it to be associated with the control then use inheritance. Derive a class from the control type and add the properties you need. Or add a field to your form.
精彩评论