If you want to allow the user access to your class properties, you could display them in a grid of some kind, or design a form to access them. But, as you probably know, there is a simpler way: just drop a
PropertyGrid
control on your form, and set it's
SelectedObject
property at run time. It then automatically fills with names, and contents, and allows the user to edit them. This is very handy, but there are a few limitations:
1) It really doesn't handle Collections well: There seems to be no way to get a notification that the collection content has changed, and the "Add" button in the Collections editor will throw an trapped exception for "constructor not found" even for basic types like
System.String
. You can get round this with a custom Collections editor, but...
2) You have to tell it "this is a file", and it is not easy to find out how to do it.
It took me around eight hours of Google / MSDN / Fiddle / swear (repeat) to work it out, but it is very simple.. Create a new WinForms project, call your form "frmMain" and drop a PropertyGrid control onto it. Rename the control "pgDetails" then:
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace PropertyGridFileBrowser
{
public partial class frmMain : Form
{
private MyTestClass tester = new MyTestClass();
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
tester.Filename = @"F:\Temp\Blue.bmp";
pgDetails.SelectedObject = tester;
}
}
public class MyTestClass
{
[Category("File")]
[Description("Source file for thumbnail and web images")]
[EditorAttribute(typeof(System.Windows.Forms.Design.FileNameEditor), typeof(System.Drawing.Design.UITypeEditor))]
public string Filename { get; set; }
public MyTestClass() { }
}
}
That's it: all code done. Just add the "
EditorAttribute
" line to each file based property. The only other thing you have to do is add a reference to "System.Design" to your project.
Remember: A PropertyGrid shows all properties with a
Public
getter:
Private
,
Internal
, and
Protected
are not shown. It allows the user to change any property which has a
Public
setter -
Private
,
Internal
and
Protected
setters cause read-only properties in the control.