2015-02-10 87 views
1

我想在PropertyGrid加載後更改WinForm PropertyGrid的幫助區域中的文本。這是我2次嘗試使用反射,但他們都無法正常工作。WinForm PropertyGrid更改幫助區域中的文本

解決方案1 ​​:我繼承PropertyGrid並檢索doccomment,它是幫助區域的控件。我有一個單獨的按鈕,調用ChangeHelpText方法來更改doccomment的文本屬性。之後,我再調用PropertyGrid的Refresh方法。但是,沒有任何變化。我也分配了PropertyGrid的HelpBackColor,也沒有任何變化。任何想法?

public void ChangeHelpText(String desc) 
{ 
    FieldInfo fi = this.GetType().BaseType.GetField("doccomment", BindingFlags.NonPublic | BindingFlags.Instance); 
    Control dc = fi.GetValue(this) as Control; 
    dc.Text = desc; 
    dc.BackColor = Color.AliceBlue; 
    fi.SetValue(this, dc); 
} 

解決方案2:PropertyGrid中的幫助文本反映了綁定類屬性的DescriptionAttribute。因此,我使用TypeDescriptor.GetProperties檢索PropertyGrid的SelectedObject的所有屬性,遍歷它們並檢索DescriptionAttribute,並使用反射將DescriptionAttribute的描述專用字段更改爲我的文本。有趣的是,如果我在重新指定DescriptionAttribute的地方放置了一個斷點,此解決方案將部分工作,因爲只有一些屬性的DescriptionAttribute被更改並反映在PropertyGrid中,而其他屬性未更改。如果我不放置斷點,則不會改變。一切都在STAThread中運行。

回答

1

第一個解決方案不起作用,因爲您正在設置控件的Text屬性,該屬性不用於顯示幫助文本。 DocComment控件有兩個標籤子控件,用於顯示幫助標題(屬性標籤)和幫助文本(屬性描述屬性值)。如果你想改變幫助文本,你可以操縱這兩個標籤。

調用更新這兩個控件的方法會更簡單。下面給出的示例代碼工作,但使用反射來調用該方法。

public class CustomPropertyGrid : PropertyGrid 
{ 
    Control docComment = null; 
    Type docCommentType = null; 

    public void SetHelpText(string title, string helpText) 
    { 
     if (docComment == null) 
     { 
      foreach (Control control in this.Controls) 
      { 
       Type controlType = control.GetType(); 
       if (controlType.Name == "DocComment") 
       { 
        docComment = control; 
        docCommentType = controlType; 
       } 
      } 
     } 
     BindingFlags aFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; 
     MethodInfo aInfo = docCommentType.GetMethod("SetComment", aFlags); 
     if (aInfo != null) 
     { 
      aInfo.Invoke(docComment, new object[] { title, helpText }); 
     } 
    } 
} 

要更改背景顏色和前景色,請使用PropertyGrid提供的屬性。

propertyGrid1.HelpBackColor = Color.BlueViolet; 
propertyGrid1.HelpForeColor = Color.Yellow;