Tag property without inheritance
Tag property is very often used to store a data associated with an object. The simple way to add support for Tag property is to create a base class with the Tag property .I don’t like this solution – the reason is simple .Sometimes I want to inherit from an existing class that doesn’t have the Tag property and I can’t change its source code .In WPF we have dependency properties that can help us in this case.
MyControl cnt = new MyControl(); cnt.SetValue(FrameworkElement.TagProperty, new Info() );
One problem – we still need to inherit from DependecyObject class.
The helper class below uses extension methods – to provide the tag functionality for your classes.
Of course, for better performance, you may change the dictionary(and methods) to be more type specific .
/// /// Implements tag functionality /// static class TagHelper { /// /// Adds the tag. /// /// The element. /// The tag. public static void AddTag(this object element, object tag) { if (!tags.ContainsKey(element)) { tags.Add(element, tag); } } /// /// Removes the tag for the specified element. /// /// The element. public static void RemoveTag(this object element ) { tags.Remove(element); } /// /// Clears the tags. /// public static void ClearTags() { tags.Clear(); } /// /// Gets the tag for the specified element. /// /// The element. /// public static object Get(this object element) { object tag; tags.TryGetValue(element, out tag); return tag; } private static Dictionary<object, object> tags = new Dictionary<object, object>(); }
Comments (3)
Note that you might have a memory leak in that code, because the dictionary is static has a reference to your object.
You could solve that using WeakReference though.
WPF allows more than just Tag Properties. Tag Properties are actually a WinForms concept. WPF allows much richer properties to be defined: Attached Properties.
See WPF Unleashed by Nathan: “Just like previous technologies such as Windows Forms, many classes in WPF define a Tag property (of type System.Object) intended for storing arbitrary custom data with each instance. But attached properties are a more powerful and flexible mechanism for attaching custom data to any object deriving from DependencyObject. It’s often overlooked that attached properties enable you to effectively add custom data to instances of sealed classes (something that WPF has plenty of)!” http://www.codeguru.com/csharp/sample_chapter/print.php/c13347__4/
To John “Z-Bo” Zabroski: I just tried to create a lightweight version of class that supports Tag property without using DependencyObject .