Minato
Minato

Reputation: 352

Customizing Properties

I'm creating some custom controls that inherit from a base custom control that has the following properties:

    public Color BorderColor
    {
        get { return BorderColor; }
        set
        {
            if (!FollowsScheme)
                BorderColor = value;
        }
    }

    public Color[] FillColors
    {
        get { return FillColors; }
        set
        {
            if (!FollowsScheme)
                FillColors = value;
        }
    }

    public bool FollowsScheme { get; set; }

I'm trying to make it so if the user sets FollowsScheme to false, only then can they edit the BorderColor and the FillColors properties. If FollowsScheme is true, then they cannot edit the two properties. In that code you can see what I tried to do and thought would work, but when I build the solution and add the control to a form, Visual Studio crashes. How should I do this?

Let me explain better, if FollowsScheme is set to true, on the OnPaint method the code will draw the control based on BorderColor and FillColors properties which is based on a static class filled with colors for the theme I designed. If FollowsScheme is set to false, then the OnPaint method will take the BorderColor and FillColors properties and calculate a new scheme and set those colors to the private properties listed and then those will be used to draw the control.

Upvotes: 1

Views: 63

Answers (2)

User 12345678
User 12345678

Reputation: 7804

Understand that when you add a control to your form, Visual Studio will run the code required to render that control so that it can be displayed in the designer.

Your code throws an StackOverflowException which subsequently causes Visual Studio to crash.

This exception is raised because your property setter is infinitely recursive. The solution is to introduce a backng field to hold the value like this:

private Color borderColor;
public Color BorderColor
{
    get { return this.borderColor; }
    set
    {
        if (!FollowsScheme)
            this.borderColor = value;
    }
}

Upvotes: 2

Mesh
Mesh

Reputation: 6472

You are setting the property inside the property setter

public Color BorderColor
{
    get { return BorderColor; }
    set
    {
        if (!FollowsScheme)
            BorderColor = value;   // BOOM!
    }
}

you need to use a backing member variable for your properties, typically like this:

private Color borderColor;
public Color BorderColor
{
    get { return borderColor; }
    set
    {
        if (!FollowsScheme)
            borderColor = value;
    }
}

Upvotes: 0

Related Questions