#156 – Using the Tag Property to Store Custom Data with an Element

In WPF, the FrameworkElement class includes a Tag property that allows storing some arbitrary data with an element.

You’d normally use the Tag property to store some custom data on an element that inherits from FrameworkElement.  In the example below, we store some custom data with two different Button objects.

        <Button Tag="Some arbitrary data" Content="Test" Height="23" Width="75" Name="btnTest" Click="btnTest_Click"/>
        <Button Tag="{StaticResource greenBrush}" Content="Test 2" Height="23" Width="75" />

However, because you can attach a dependency property value to any object deriving from DependencyObject, you can also use the Tag property to attach data to objects that don’t derive from FrameworkElement or to dependency objects that are otherwise sealed.

            // ListView has a GridView as its view
            GridView gv1 = (GridView)listView1.View;

            // Attach a Tag to the GridView -- a Person object
            gv1.SetValue(FrameworkElement.TagProperty, new Person("Herodotus"));