views:

562

answers:

1

I've got a PropertyGrid that reflects properties of my class.

I am watching the PropertyValueChanged event and notice that PropertyValueChangedEventArgs provides the GridItem that was changed.

That GridItem has a Tag property that I can get. I don't see how to set the Tag property of a GridItem to a value.

How can I set the Tag property of a GridItem?

A: 

...My original answer was pretty far off so I'm revamping the entire thing in this update...

Here's what I would do if I needed to meet this requirement.

Create an attribute that will be used to pre-define the Tag value of your GridItem; let's call it TagAttribute. It could be as simple as this:

public class TagAttribute : Attribute
{
    public string TagValue { get; set; }

    public TagAttribute ( string tagValue )
    {
        TagValue = tagValue;
    }
}

To pre-define the Tag value, you would just need to decorate the desired property with this attribute.

public class MyAwesomeClass
{
    ...
    [TagAttribute( "This is my tag value." )]
    [CategoryAttribute( "Data" )]
    public string MyAwesomeProperty { get; set; }
    ...
}

I would then inherit the PropertyGrid and override the OnPropertyValueChanged event in order to set the Tag property of the GridItem to coincide with the pre-defined TagAttribute.

public partial class InheritedPropertyGrid : PropertyGrid
{
    ...    
    protected override void OnPropertyValueChanged ( PropertyValueChangedEventArgs e )
    {
        var propertyInfo = SelectedObject.GetType().GetProperty( e.ChangedItem.PropertyDescriptor.Name );
        var tagAttribute = propertyInfo.GetCustomAttributes( typeof( TagAttribute ) , false );

        if ( tagAttribute != null )
            e.ChangedItem.Tag = ( (TagAttribute)tagAttribute[0] ).TagValue;

        base.OnPropertyValueChanged( e );
    }    
    ...
}

Now when you hook into the OnPropertyValueChanged of this "InheritedPropertyGrid", the Tag property will be set to what you defined on the property.

Steve Dignan
ChangedItem is a GridItem object. I want to set the tag property when that GridItem is created. But the GridItem is a reflection of a property of my class.When I create that property I use attributes like "Description", "Browseable" etc. I thought there might be a "Tag" attribute.
mohnston
the only problem with this method is that it will only allow setting static data.
Stan R.
In the scope of the OP's question, I don't think this would be considered a "problem" as the request is to pre-define a "Tag" value (which this accomplishes).
Steve Dignan