简体   繁体   中英

C# How to set the default value of an object in the propertygrid?

I have an object which inherits from Button. This button is a property of an object which inherit from TableLayoutPanel. The property is called MyButton :

[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
**[DefaultValue(??? Something Like Visible = false ???)]**
public CustomButton MyButton
{
    get { return _button; }
    set { _button = value; }
}

Now, in the designer, I want to set the Visible property of MyButton to be false. Default the Visible property true, but in this case, I want it to be false.

How can I do this?

Because your value is not a constant value it cannot be used with DefaultValueAttribute since these values are required at compile time. Instead you can disregard DefaultValueAttribute and in the constructor you can initialize the MyButton attribute with a custom instance of CustomButton with the default attributes set on it. The only irregularity here is that in the property grid the property value will appear bold as if the user had changed it.

Here is an example:

public YourCustomControlClass()
{
    this.MyButton = new CustomButton { Visible = false; };
}

in your MyButton Class, remove anything you've added trying to override the Visible property add following code:

public MyButton()
{
    this.Visible=false;
}

Rebuild it, then add a new Mybutton instance to your form, you can see its visible property in the Designer is set to False now.

Override the property and then set the default value:

[DefaultValue(false)]
new public bool Visible
{
  get { return base.Visible; }
  set { base.Visible = value; }
} 

Hope this will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM