views:

369

answers:

1

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?

Thanks.

+1  A: 

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;
        }
    }
}
Philip Wallace
Ah I see, I will give this a shot. Thanks so much.
Nathan
Philip is this a different process then the one here? http://www.c-sharpcorner.com/UploadFile/mgold/PropertyGridInCSharp11302005004139AM/PropertyGridInCSharp.aspxAlso, if you know how can I add a combo box to the property grid?
Nathan
Take a look at this article:http://www.codeproject.com/KB/tabs/PropertyGridValidation.aspx
Philip Wallace
Would you be willing to send me an email at [email protected] so I could have your email address? I would like to ask a couple more questions and email is easier then this.
Nathan
Ask them through here, then at least the rest of SO can contribute to/benefit from the answer.
Philip Wallace
In my user control I have had to replace the get { return this.Height;} with get {return _height;} because I was getting a stackoverflow exception. I read up on this and it seems like this is due to a recursion issue. I have also successfully bound the properties to the control but how do I issue the property changes back to the control so it updates on the control on the form?
Nathan
Call Refresh() - it should do the trick.
Philip Wallace
Where am I calling Refresh() at? On the user control when the value gets set?
Nathan
On the property grid when your User Control properties have changed.
Philip Wallace