Question

I am writing an application which is going to allows users to change the properties of a text box or label and these controls are user controls. Would it be easiest to create a separate class for each user control which implements the properties I want them to be able to change and then bind those back to the user control? Or is there another method I am overlooking?

Was it helpful?

Solution

Create a custom Attribute, and tag the properties you want the user to edit with this attribute. Then set the BrowsableAttribute property on the property grid to a collection containing only your custom attribute:

public class MyForm : Form
{
    private PropertyGrid _grid = new PropertyGrid();

    public MyForm()
    {
        this._grid.BrowsableAttributes = new AttributeCollection(new UserEditableAttribute());
        this._grid.SelectedObject = new MyControl();
    }
}

public class UserEditableAttribute : Attribute
{

}

public class MyControl : UserControl
{
    private Label _label = new Label();
    private TextBox _textBox = new TextBox();

    [UserEditable]
    public string Label
    {
        get
        {
            return this._label.Text;
        }
        set
        {
            this._label.Text = value;
        }
    }

    [UserEditable]
    public string Value
    {
        get
        {
            return this._textBox.Text;
        }
        set
        {
            this._textBox.Text = value;
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top