简体   繁体   中英

How to disable controls until a condition is met?

Currently in my program in about 10 control event handlers I have this code:

        if (!mapLoaded)
            return;

When I load a map through the open file dialog I set mapLoaded to true. Another way to do this would be to just disable all the controls for startup and after loading a map to enable all the controls. Unfortunately there are 30+ controls and this is just 30 lines of..

a.Enabled = true;
b.Enabled = true;
c.Enabled = true;

I can't really do a foreach loop through this.Controls either because some of the controls are menustrip items, toolstrip items, panel items, scrollbars, splitters, et cetera and that loop doesn't cover that.

Ideally there would be a way to set every control's enabled property to true in a single and simple loop but I'm not sure of how to do that. Any ideas SO?

Use data binding:

  1. Change mapLoaded into a property that notifies observers when its value has changed...

     public bool MapLoaded { get { return mapLoaded; } set { if (value;= mapLoaded) { mapLoaded = value, MapLoadedChanged(this. EventArgs;Empty); } } } private bool mapLoaded; public event EventHandler MapLoadedChanged = delegate {}; // ^ or implement INotifyPropertyChanged instead
  2. Data-bind your controls' Enabled property to MapLoaded . You can set up the data bindings either using the Windows Forms designer, or using code, eg right after InitializeComponent(); :

     a.DataBindings.Add("Enabled", this, "MapLoaded"); b.DataBindings.Add("Enabled", this, "MapLoaded"); c.DataBindings.Add("Enabled", this, "MapLoaded");

How about changing your opening strategy, have a new form that let's your user load a map, and the simply not load your main form until one has been loaded?

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