6

I'm working on a business application that use the PropertyGrid. My project leader want me to localize the texts in the PropertyGrid at runtime. Hurray!!! irony

I have tried many days to localize the PropertyGrid. But I have trouble changing the attributes Description and Category at runtime. Changing the DisplayName works fine.

I have made a simple example to reproduce the issue: Create a Windows Form application and from the ToolBox add a PropertyGrid and a Button with default settings.

Here is the class I would like to display in the PropertyGrid:

class Person
{
    int age;

    public Person()
    {
        age = 10;
    }

    [Description("Person's age"), DisplayName("Age"), Category("Fact")]
    public int Age
    {
        get { return age; }
    }
}

In the Form's constructor; I create the Person object and display it in the PropertyGrid.

    public Form1()
    {
        InitializeComponent();
        propertyGrid1.SelectedObject = new Person();
    }

The button is used to change the DisplayName, Description and Category attributes at runtime.

    private void button1_Click(object sender, EventArgs e)
    {
        SetDisplayName();
        SetDescription();
        SetCategory();

        propertyGrid1.SelectedObject = propertyGrid1.SelectedObject;  // Reset the PropertyGrid
    }

The SetDisplayName() method works fine and actually changes the DisplayName of the property in runtime!

    private void SetDisplayName()
    {
        Person person = propertyGrid1.SelectedObject as Person;
        PropertyDescriptor descriptor = TypeDescriptor.GetProperties(person)["Age"];
        DisplayNameAttribute attribute = descriptor.Attributes[typeof(DisplayNameAttribute)] as DisplayNameAttribute;
        FieldInfo field = attribute.GetType().GetField("_displayName", BindingFlags.NonPublic | BindingFlags.Instance);
        field.SetValue(attribute, "The age");
    }

SetDescription() and SetCategory() methods are almost identical to the SetDisplayName() method, except for some type changes and strings to access the private member of each attributes.

    private void SetDescription()
    {
        Person person = propertyGrid1.SelectedObject as Person;
        PropertyDescriptor descriptor = TypeDescriptor.GetProperties(person)["Age"];
        DescriptionAttribute attribute = descriptor.Attributes[typeof(DescriptionAttribute)] as DescriptionAttribute;
        FieldInfo field = attribute.GetType().GetField("description", BindingFlags.NonPublic |BindingFlags.Instance);
        field.SetValue(attribute, "Age of the person");
    }

    private void SetCategory()
    {
        Person person = propertyGrid1.SelectedObject as Person;
        PropertyDescriptor descriptor = TypeDescriptor.GetProperties(person)["Age"];
        CategoryAttribute attribute = descriptor.Attributes[typeof(CategoryAttribute)] as CategoryAttribute;
        FieldInfo[] fields = attribute.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
        FieldInfo field = attribute.GetType().GetField("categoryValue", BindingFlags.NonPublic | BindingFlags.Instance);
        field.SetValue(attribute, "Info");
    }

Both SetDescription() and SetCategory() methods compile and run but don't effext the ProperytGrid. After the last line of each method you can use the IntelliSense to see that the the Attribute object (DescriptionAttribute and CategoryAttribute) has a member that has changed.

After running these three methods and resetting the PropertyGrid (see button1 click method); the PropertyGrid has only changed the DisplayName attribute. The Description and the Category attributes are unchanged.

I would really like some help to solve this issue. Please any suggestion or solutions?

Note 1: I don't want any responses saying that this is impossible and the attributes can only be set at design time. That is not true! This article from CodeProject.com show an example how to localize the PropertyGrid and to change the attributes in runtime. Unfortunately I have problem scoping the example for those parts I need to solve this issue.

Note 2: I would like to avoid using resouce files. This is due to the localization is located in different language files. Each file contain a bunch of indices, each with a string value. All indices and string values are loaded into Dictionary object. To access a string the index is used to access it. I most, unfortunately, use this solution.

Best regards, /Mc_Topaz

5 Answers 5

4

Here is a good article for Globalized-property-grid

You can give many resource file for the Person ,than will the propery-grid will localize.

Here is three step:

  1. inherit from GlobalizedObject
  2. Give the resource file for Person with the same name (eg.Person.zh-cn.resx)
  3. change the thread's cuture which you want to display.

You can try ,Good Luck!

2
  • Thanks, but I don't think I can use that solution... :( Let me explain: The localization is located in language files. The files are read during start of the application. Each language is loaded into an Dictionary<int, string>. By hard coding the index in the code, the correct string of current language is returned from the dictionary. Unfortunately I must that solution due to other benefits.
    – Mc_Topaz
    Jun 28, 2014 at 17:22
  • Continue with the comment: That is way I used strings to change attributes in my three example methods (SetDisplayName, SetDescription and SetCategory). I would like to stay with that solution IF possible. Or is there a way to create a resource files in runtime for each language and populate it with the localization I have from the Dictionaries? /Mc_Topaz
    – Mc_Topaz
    Jun 28, 2014 at 17:23
2

What you could do is reuse the DynamicTypeDescriptor class described in my answer to this question here on SO: PropertyGrid Browsable not found for entity framework created property, how to find it?

like this:

  public Form1()
  {
      InitializeComponent();

      Person p = new Person();

      DynamicTypeDescriptor dt = new DynamicTypeDescriptor(typeof(Person));
      propertyGrid1.SelectedObject = dt.FromComponent(p);
  }

  private void button1_Click(object sender, EventArgs e)
  {
      DynamicTypeDescriptor dt = (DynamicTypeDescriptor)propertyGrid1.SelectedObject;
      DynamicTypeDescriptor.DynamicProperty dtp = (DynamicTypeDescriptor.DynamicProperty)dt.Properties["Age"];

      dtp.SetDisplayName("The age");
      dtp.SetDescription("Age of the person");
      dtp.SetCategory("Info");

      propertyGrid1.Refresh();
  }
2
  • Thanks! I solved the issue with xudong125 solution. Your solution seem similar so I guess it basically the same. I have marked xudong125 answer as the solution, so any other can benefit from it as well as your solution.
    – Mc_Topaz
    Jun 29, 2014 at 20:55
  • I have tried this, but nothing happens when I execute your code. It is as if it doesn't even exist. Do you have any idea why that might be? I have not forgotten to refresh the grid after changing the properties.
    – A Petrov
    Jun 9, 2015 at 14:50
2

xudong125 answer solves the issue! I managed to work around the resource files solution by using a static source instead. It's to complicated to explain...

But creating classes implementing ICustomTypeDescriptor and PropertyDescriptor is the way to go.

The key was to override DisplayName, Description and Category methods in the sub class of the PropertyDescriptor class. In these overriden methods I pointed to a public static source and managed to get the strings I wanted.

/Mc_Topaz

0

I have a different reason to change the property description and found a fairly crude but much simpler solution for just correcting the description that is shown in the grid. Advantage for me was that the class of the object shown in the property grid required much less change.

My situation was the following: I have two boolean properties A and B, where B only can be used if A is set. If A is False, I want to make B read-only and set its description to something like "This property can only be used if you set 'A' to True". In the object code I set the Description attribute of B to this message, similar to how Mc_Topaz does that.

To only set the description that is shown for the selected property to its correct current value, I use the following SelectedGridItemChanged event handler for my PropertyGrid named pgConfig:

    private void pgConfig_SelectedGridItemChanged(object sender, SelectedGridItemChangedEventArgs e)
    {
      GridItem giSelected = e.NewSelection;
      if ((giSelected != null) && (giSelected.PropertyDescriptor != null))
      {
        string sDescription = GetCurrentPropertyDescription(giSelected.PropertyDescriptor.Name);
        if ((sDescription != null) && (sDescription != giSelected.PropertyDescriptor.Description))
        {
          MethodInfo miSetStatusBox = pgConfig.GetType().GetMethod("SetStatusBox", BindingFlags.NonPublic | BindingFlags.Instance);
          if (miSetStatusBox != null)
            miSetStatusBox.Invoke(pgConfig, new object[] { giSelected.PropertyDescriptor.DisplayName, sDescription });
        }
      }
    }

In the code sample, GetCurrentPropertyDescription is a private function that retrieves the current property description of the object being shown in the property grid (m_da.Config in my case):

    private string GetCurrentPropertyDescription(string sPropertyName)
    {
      PropertyDescriptor oPropDescriptor = TypeDescriptor.GetProperties(m_da.Config.GetType())[sPropertyName];
      if (oPropDescriptor != null)
      {
        DescriptionAttribute oDescriptionAttr = (DescriptionAttribute)oPropDescriptor.Attributes[typeof(DescriptionAttribute)];
        if (oDescriptionAttr != null)
          return oDescriptionAttr.Description;
      }
      return null;
    }

My solution is less suitable than huoxudong125's if you want full globalization, but if you just want dynamic descriptions for some of your properties without changing the inheritance of the object being shown, it is an option.

Disadvantage of my method is that the underlying cached PropertyDescriptor objects of the grid are never updated, so SetStatusBox will always be called twice if a property with changed description is selected, which is inefficient.

0

The solution of huoxudong125 is one possible solution. I'd like to offer another one (but without talking about how to change the culture stuff at runtime - you can google that yourself ;) ). For myself I started with using localized subclasses for DisplayName, Description and Category.

As we know, DisplayName does update to current culter when PropertyGrid is updated, but Description and Category do not. I think the reason for this is on reflection level, when PropertyGrid requests category and description. As you can see, those values are cached on first read but displayName is not. To tackle that I developed two solution (where the first one is weird and I do not understand why that works myself..). Both revolve around an extra TypeDescriptionProvider

The base

First goes the custom TypeDescriptionProvider, which can be bound to any class via attribute:

internal class UpdateableGlobalizationDescriptionProvider<TTargetType> : TypeDescriptionProvider
{
    private static TypeDescriptionProvider defaultTypeProvider = TypeDescriptor.GetProvider(typeof(TTargetType));

    public UpdateableGlobalizationDescriptionProvider() : base(defaultTypeProvider) { }

    public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
    {
        var result = base.GetTypeDescriptor(objectType, instance);
        return new ForcedGlobalizationTypeDescriptor(result);
    }
}

First solution

This one revolves around "just get it done"... Add a CustomTypeDescriptor implementation, which wraps original PropertyDescriptor instances with the custom ones:

internal class ForcedGlobalizationTypeDescriptor : CustomTypeDescriptor
{
    readonly ICustomTypeDescriptor inner;

    public ForcedGlobalizationTypeDescriptor(ICustomTypeDescriptor typeDescriptor) : base(typeDescriptor)
    {
        inner = typeDescriptor;
    }

    public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
    {
        // First solution
        var result = base.GetProperties(attributes);
        var transformed = result.OfType<PropertyDescriptor>().Select(d => new ForcedPropertyDescriptor(d)).ToArray();
        return new PropertyDescriptorCollection(transformed);
    }
}

and outer the PropertyDesciptor simply returns values from the wrapped PropertyDescriptor. The simplest implementation for PropertyDescriptor I found - tell me, if there is a shorter one, please.

internal class ForcedPropertyDescriptor : PropertyDescriptor
{
    private PropertyDescriptor innerDescriptor;
    public ForcedPropertyDescriptor(PropertyDescriptor descriptor) : base(descriptor)
    {
        innerDescriptor = descriptor;
    }
    // important:
    public override string Category => base.Category;
    public override string Description => base.Description;

    public override Type ComponentType => innerDescriptor.ComponentType;
    public override bool IsReadOnly => innerDescriptor.IsReadOnly;
    public override Type PropertyType => innerDescriptor.PropertyType;
    public override bool CanResetValue(object component) => innerDescriptor.CanResetValue(component);
    public override object GetValue(object component) => innerDescriptor.GetValue(component);
    public override void ResetValue(object component) => innerDescriptor.ResetValue(component);
    public override void SetValue(object component, object value) => innerDescriptor.SetValue(component, value);
    public override bool ShouldSerializeValue(object component) => innerDescriptor.ShouldSerializeValue(component);
}

I think it works, because for every read of category or description there is a new ForcedPropertyDescriptor, which has not cached the value, yet. At the same time this is a drawback: for like every request on the Category or Description propery a new instance of ForcedPropertyDescriptor is created, while Microsoft's implementation seems to cache craeated PropertyDescriptors somewehere.

Second solution

To avoid that instance creation every time, I simply stored every seen ProperyDescriptor created by ForcedGlobalizationTypeDescriptor in a set. And as soon as a localization change appears, that set gets called to reset it's items cached values:

internal class DescriptorReset
{
    public static DescriptorReset Default { get; } = new DescriptorReset();
    private HashSet<MemberDescriptor> descriptors = new HashSet<MemberDescriptor>();

    public void Add(MemberDescriptor descriptor)
    {
        descriptors.Add(descriptor);
    }

    private void RunUpdate()
    {
        if (descriptors.Count == 0)
            return;
        FieldInfo category, description;
        category = typeof(MemberDescriptor).GetField(nameof(category), BindingFlags.NonPublic | BindingFlags.Instance);
        description = typeof(MemberDescriptor).GetField(nameof(description), BindingFlags.NonPublic | BindingFlags.Instance);
        foreach (var descriptor in descriptors)
        {
            category.SetValue(descriptor, null);
            description.SetValue(descriptor, null);
        }
    }
}

The RunUpdate method uses Reflection to reset inner fields to null, so on the next call to corresponding properties the localized values are read again.

All you need now is some magic to call RunUpdate at the right moment. For myself I have a class in my core solution, which provides a method to set a new CultureInfo. When called, it sets the default ui culture and the default culture to the new CultureInfo and raises two events: the first one is to update all internal logic and the second one is for everything based on internal logic, like the GUI.

And since I do not know where and how long Microsoft's PropertyDescriptors are stored, I created a HashSet with WeakReference (based on WeakHashTable) to store corresponding references.

Usage

Simply append the DescriptionProvider class to your class shown in PropertyGrid:

[LocalizedDescription(nameof(MyClass), typeof(MyTextResource))]
[TypeDescriptionProvider(typeof(ForcedGlobalizationTypeDescriptor<MyClass>))]
class MyClass 
{
    // ...

The way your LocalizedDescription works, depends on you...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.