2010-09-28 12 views
2

我正在用一些可以讓我更好地定製我的UI的東西來替換我的屬性網格。我在表單上放置了一個按鈕,我希望點擊該按鈕時會彈出一個CollectionEditor並允許我修改代碼。當我使用PropertyGrid時,我需要做的就是向指向我的CollectionEditor的屬性添加一些屬性,並且它工作正常。但是,我如何手動調用CollectionEditor?謝謝!有什麼方法可以在屬性網格之外使用CollectionEditor?

回答

10

在這裏找到了答案:http://www.devnewsgroups.net/windowsforms/t11948-collectioneditor.aspx

萬一上面鏈接網站消失的某一天,這裏是它的要點。但是,代碼是從上面的鏈接逐字記錄的;評論是我的。

假設你有一個帶有ListBox和一個按鈕的窗體。如果你想編輯使用CollectionEditor ListBox中的項目,你會做你的事件處理程序如下:

private void button1_Click(object sender, System.EventArgs e) 
{ 
    //listBox1 is the object containing the collection. Remember, if the collection 
    //belongs to the class you're editing, you can use this 
    //Items is the name of the property that is the collection you wish to edit. 
    PropertyDescriptor pd = TypeDescriptor.GetProperties(listBox1)["Items"]; 
    UITypeEditor editor = (UITypeEditor)pd.GetEditor(typeof(UITypeEditor)); 
    RuntimeServiceProvider serviceProvider = new RuntimeServiceProvider(); 
    editor.EditValue(serviceProvider, serviceProvider, listBox1.Items); 
} 

現在,你需要做的下一件事就是創建RuntimeServiceProvider()。這是在上面的鏈接海報寫來實現此代碼:

public class RuntimeServiceProvider : IServiceProvider, ITypeDescriptorContext 
{ 
    #region IServiceProvider Members 

    object IServiceProvider.GetService(Type serviceType) 
    { 
     if (serviceType == typeof(IWindowsFormsEditorService)) 
     { 
      return new WindowsFormsEditorService(); 
     } 

     return null; 
    } 

    class WindowsFormsEditorService : IWindowsFormsEditorService 
    { 
     #region IWindowsFormsEditorService Members 

     public void DropDownControl(Control control) 
     { 
     } 

     public void CloseDropDown() 
     { 
     } 

     public System.Windows.Forms.DialogResult ShowDialog(Form dialog) 
     { 
      return dialog.ShowDialog(); 
     } 

     #endregion 
    } 

    #endregion 

    #region ITypeDescriptorContext Members 

    public void OnComponentChanged() 
    { 
    } 

    public IContainer Container 
    { 
     get { return null; } 
    } 

    public bool OnComponentChanging() 
    { 
     return true; // true to keep changes, otherwise false 
    } 

    public object Instance 
    { 
     get { return null; } 
    } 

    public PropertyDescriptor PropertyDescriptor 
    { 
     get { return null; } 
    } 

    #endregion 
} 
+1

+1夢想家ic解決方案。似乎唯一的缺點是我看不到用戶是否按下了「取消」。我錯過了什麼嗎? – Brad 2013-03-29 11:43:09

1

因爲我不能發表評論,我會在這裏發佈這樣的:

您可以通過添加一個Click事件得到的DialogResult該CollectionEditor的okButton在WindowsFormsEditorService.ShowDialog

public System.Windows.Forms.DialogResult ShowDialog(Form dialog) 
{ 
    ((System.Windows.Forms.Button)dialog.Controls.Find("okButton", true)[0]).Click += WindowsFormsEditorService_Click; 
    return dialog.ShowDialog(); 
} 

...

private void WindowsFormsEditorService_Click(object sender, EventArgs e) 
{ 
    dr = DialogResult.OK; 
} 
相關問題