Expose editable properties in a Windows Forms PropertyGrid
PropertyGrid.SelectedObject exposes an object's public properties for inspection and editing. Component-model attributes control how those properties appear. They do not initialize the underlying values.
The same attributes help a custom control present a deliberate design-time surface instead of exposing every implementation detail.
Display an editable object
On Windows, create a project with dotnet new winforms -n PropertyDemo -f net10.0, replace Program.cs, then run dotnet run --project PropertyDemo.
using System.ComponentModel;
using System.Windows.Forms;
internal static class Program {
[STAThread]
private static void Main() {
Application.EnableVisualStyles();
var options = new Options();
var form = new Form { Text = "Options", Width = 480, Height = 300 };
form.Controls.Add(new PropertyGrid { Dock = DockStyle.Fill, SelectedObject = options });
Application.Run(form);
}
}
public sealed class Options {
[Category("Display"), Description("Heading shown above the list."), DefaultValue("Items")]
public string Heading { get; set; } = "Items";
[Browsable(false)]
public Guid InternalId { get; } = Guid.NewGuid();
}
The grid displays Heading under Display, with its description in the help pane. Editing it changes the same Options object. InternalId is hidden.
Expose a UserControl's Text deliberately
For a custom UserControl, override Text and apply [Browsable(true)] plus [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] when the designer should persist it. Forward the value to the intended child control and retain the base property's change behavior if consumers rely on TextChanged.
DefaultValue("Items") describes the default to designers. The initializer actually creates that value. Keep those two declarations consistent. Use ReadOnly(true) for a visible, noneditable property and a TypeConverter when a complex value needs a custom textual representation.
Official references


Author: Herman Schoenfeld