Winform Custom Control: DesignMode doesn't ret

2020-01-31 01:05发布

I learnt about DesignMode here How to refresh a winform custom control at design time after changing a property

But when in the constructor of my custom control I use it, it never returns true so when I drag and drop my custom control it always show max = 200 so what's wrong?

if (this.DesignMode)
{                
    this.Min = 0;
    this.Max = 100;
} 
else 
{
    this.Min = 0;
    this.Max = 200;            
}

this.LabMin.Text = this.Min.ToString();
this.LabMax.Text = this.Max.ToString();  

标签: c# winforms
4条回答
▲ chillily
2楼-- · 2020-01-31 01:40

It could be that the control must also must have an ISite associated with it, otherwise it will always return false

The design mode indicator is stored in the ISite; therefore, if the Component does not have an ISite associated with it, the value of this property is false.

Source: MSDN

Edit: Also see this post as someone had a similar problem to the one you're facing

Windows Forms designer and DesignMode property issues

Edit 2: I also found a site that seems to indicate that this is a common problem with custom controls but it also lists some work arounds. You can find it here:

Custom Control Design Mode Problem

查看更多
我只想做你的唯一
3楼-- · 2020-01-31 01:45

For what I remember in the Ctor the DesignMode property has not its value yet. You should use it after initializeComponents or in an event handler.

查看更多
贪生不怕死
4楼-- · 2020-01-31 01:47

LicenseManager.UsageMode is intended for this.

It is in fact the only reliable way to detect if your control is in design mode or not. It's only valid during the constructor, but it can easily be stored in a field of the class for later reference.

The DesignMode property for nested controls will be false even when the container control is in design mode.

查看更多
Evening l夕情丶
5楼-- · 2020-01-31 01:51

For any that arrive at this topic, there's another way to handle this.

If you implement ISupportInitialize for your winforms control, the designer code will call begin/end initialize of your control.

then, for all of your design time and runtime changes, you can adjust in the EndInitialization method. by that time, the Site.DesignMode property will have been set to True/False.

I also like to add a class level boolean, i.e. bool _initializing = false; so i can track that state in other places.

this seems to be the least "hacky" way of handling such stuff.

查看更多
登录 后发表回答