How to refresh localized attributes in PropertyGrid

本小妞迷上赌 提交于 2019-12-06 00:23:16

We can reproduce this in a simple but complete example (that simply adds a counter onto the name, to represent each translation as it happens):

[STAThread]
static void Main()
{
    Application.EnableVisualStyles();
    Show();
    Show();
}
static void Show()
{
    using(var grid = new PropertyGrid
        {Dock = DockStyle.Fill, SelectedObject = new Foo { Bar = "def"} })
    using(var form = new Form { Controls = { grid }})
    {
        form.ShowDialog();
    }
}

class Foo
{
    [CheekyDisplayName("abc")]
    public string Bar { get; set; }
}
public class CheekyDisplayNameAttribute : DisplayNameAttribute
{
    public CheekyDisplayNameAttribute(string resourceId)
    : base(GetMessageFromResource(resourceId))
    { }
    private static string GetMessageFromResource(string resourceId)
    {
        return resourceId + Interlocked.Increment(ref counter);
    }

    private static int counter;
}

This demonstrates that the attribute is being cached between calls. Perhaps the easiest way to fix this is to delay the translation to the time that DisplayName is queried:

public class CheekyDisplayNameAttribute : DisplayNameAttribute
{
    public CheekyDisplayNameAttribute(string resourceId)
        : base(resourceId)
    { }
    private static string GetMessageFromResource(string resourceId)
    {
        return resourceId + Interlocked.Increment(ref counter);
    }
    public override string DisplayName
    {
        get { return GetMessageFromResource(base.DisplayName); }
    }
    private static int counter;
}

However, note that this can be called lots of times (36 per showing); you might want to cache the value along with the culture it was cached for:

    private CultureInfo cachedCulture;
    private string cachedDisplayName;
    public override string DisplayName
    {
        get
        {
            var culture = CultureInfo.CurrentCulture;
            if (culture != cachedCulture)
            {
                cachedDisplayName = GetMessageFromResource(base.DisplayName);
                cachedCulture = culture;
            }
            return cachedDisplayName;
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!