我正在替换我的属性网格,这将允许我更好地自定义我的UI。我在表单上放了一个按钮,我希望点击它时会弹出一个CollectionEditor并允许我修改我的代码。当我使用PropertyGrid时,我需要做的就是向指向我的CollectionEditor的属性添加一些属性并且它有效。但是如何手动调用CollectionEditor呢?谢谢!
答案 0 :(得分:10)
在这里找到答案:http://www.devnewsgroups.net/windowsforms/t11948-collectioneditor.aspx
以防上面链接的网站有一天会消失,这就是它的要点。但是,代码是从上面的链接逐字的;评论是我的。
假设您有一个带有ListBox和按钮的表单。如果您想使用CollectionEditor编辑ListBox中的项目,您可以在EventHandler中执行以下操作:
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)
由于我无法发表评论,我将在此发布:
您可以通过在WindowsFormsEditorService.ShowDialog中的CollectionEditor的okButton上添加Click事件来获取DialogResult
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;
}