开发者

Visual Studio 2008 Form Designer messes up boolean properties values

I have a very annoying problem I'm trying to solve for couple of weeks. I have a WinForms C# project where I developed my custom control (ListView + ToolStrip with ToolStripButtons). This control is used in different forms inside solution - but in other projects. For different forms I need to make certain buttons visible or hidden, so I have added to my control corresponding properties like

    public Boolean DeleteButtonVisible
    {
        get
        {
            return tsbDelete.Visible;
        }
        set
        {
            tsbDelete.Visible = value;
        }
    }

Some buttons are visible by default, some are hidden. In designer when editing a form with my control I'm able to change those properties, buttons on control become visible or hidden as they should. But every time I'm changing anything in my control source file in all forms those properties are reset to default values regardless of what I have set in designer and I have to restore those values manually. Well, I'm using a so开发者_运维百科urce control so this is not that hard, but performing "Undo" on a couple dozen of files every time I change a bit in another file is a damn disaster.

I have tried to use [DesignerSerializationVisibility] attribute to fix this issue. If I used it with value "Hidden" it didn't do any good at all - values were just not saved. "Content" made buttons randomly disappear even if by default they were visible. "Visible" lead to no effect, as this is default value...

I don't want to set every button visibility for every form in my code - this is just not the way it should be done.

Does anyone know something about this?


Yes, the Control.Visible property is special. The getter does not return the last assigned value, it only returns true when the control is actually visible. That can have side-effects, you've found one. In this case probably induced when the control switches out of design mode. To do this correctly, you must store the assigned state in a backing variable. Like this:

    private bool tsbDeleteVisible;

    public bool DeleteButtonVisible {
        get { return tsbDeleteVisible; }
        set { tsbDelete.Visible = tsbDeleteVisible = value; }
    }

Be sure to initialize the default value of the backing variable to the default value of tsbDelete.Visible. Use the constructor to be sure.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜