2012-08-30 21 views
3

我有我的本地化屬性,如問題:如何刷新本地化的屬性在PropertyGrid中

public class LocalizedDisplayNameAttribute : DisplayNameAttribute 
{ 
    public LocalizedDisplayNameAttribute(string resourceId) 
     : base(GetMessageFromResource(resourceId)) 
    { } 

    private static string GetMessageFromResource(string resourceId) 
    { 
     var propertyInfo = typeof(Lockit).GetProperty(resourceId, BindingFlags.Static | BindingFlags.Public); 
     return (string)propertyInfo.GetValue(null, null); 
    } 
} 

當我使用屬性與此屬性它在PropertyGrid中的局部,但是當我改變當前CultureInfo它不不會刷新,即使我再次創建此PropertyGrid。我已經嘗試通過手動調用屬性:

foreach (PropertyInfo propertyInfo in myPropertiesInfoTab) 
{ 
    object[] custom_attributes = propertyInfo.GetCustomAttributes(false); 
} 

屬性構造函數被調用,而新創建的PropertyGrid中仍然有舊文化的顯示名稱(總是像第一次創建相同的值)的屬性。

它在我重新啓動應用程序時起作用,但我不想這樣做。有沒有解決方法?

回答

2

我們可以在一個簡單但完整的示例重現此(僅添加計數器上的名字,以表示每個翻譯,因爲它發生):

[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; 
} 

這表明屬性被緩存在通話之間。也許是解決這一問題的最簡單方法是翻譯推遲到DisplayName查詢時間:

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; 
} 

但是,請注意,這可以被稱爲很多次(36%顯示);你可能想緩存價值以及它被緩存的文化:

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; 
     } 
    } 
相關問題