Prevent Winforms Designer from creating property values ​​for inherited controls

I have a custom one DataGridView, let's say this:

public MyGridView : DataGridView
{
    public MyGridView()
    {
         BackgroundColor = Color.Red;
    }
}

Now, when I use this control in a project using a constructor, for some reason it also needs to set a property in the designer.cs file.

So, in the constructor file, I would:

this.MyGridView1.BackgroundColor = System.Drawing.Color.FromArgb((byte)(int)255, (byte)(int)0, (byte)(int)0);

The problem with this is that it does not allow me to change the color in my constructor MyGridView, without having to go through all the forms in which I used to manage and change it to one instance, my user control is useless.

With some properties that virtual getter offers, this is not a problem, but most properties do not have it.

How can I prevent the constructor from creating this code?

+3
4

, , , [DefaultValue] . Color, . , , , . , ColorConverter, .

PropertyGrid "" , . "Xxxx", :

  • DefaultXxxx, ,
  • ResetXxxx(), , , Reset
  • ShouldSerializeXxxx(), , false, .

:

public class MyGridView : DataGridView {
    public MyGridView() {
        this.BackgroundColor = DefaultBackgroundColor;
    }
    public new Color BackgroundColor {
        get { return base.BackgroundColor; }
        set { base.BackgroundColor = value;  }
    }
    private bool ShouldSerializeBackgroundColor() {
        return !this.BackgroundColor.Equals(DefaultBackgroundColor);
    }
    private void ResetBackgroundColor() {
        this.BackgroundColor = DefaultBackgroundColor;
    }
    private static Color DefaultBackgroundColor {
        get { return Color.Red; }
    }
}

, ResetBackgroundColor() , , , .

+8

InitLayout DesignMode. DesignMode ctor, Designmode , . : .

public class MyGridView : DataGridView
{

    protected override void InitLayout()
    {
        base.InitLayout();

        if (!DesignMode)
            BackgroundColor = Color.Red;
    }
}
+2

DefaultValue :

public class MyGridView : DataGridView
{
    public MyGridView()
    {
        BackgroundColor = Color.Red;
    }

    [DefaultValue(typeof(Color), "Red")]
    public new Color BackgroundColor
    {
        get { return base.BackgroundColor; }
        set { base.BackgroundColor = value; }
    }
}
+2

, , , ,

public static class Extensions
{
    public static void ApplyStyle( this DataGridView dataGridView )
    {
        dataGridView.RowHeadersVisible = false;
        ...
    }
}
0
source

Source: https://habr.com/ru/post/1526426/


All Articles