简体   繁体   中英

Accessing static data in UserControl constructor bug in designer

I need to access external data at the loading of a UserControl (in constructor or load event).

It works fine in run mode but in VS Designer mode it throws a NullReferenceException because in the instance the static data is not instantiated.

public partial class MyControl : UserControl
{
    public MyControl()
    {
        InitializeComponent();

        // Problem when accessing external data
        Foo( AnotherClass.MyStaticData );
    }

    private void Foo(Data d)
    {
        //...
    }
}

How can I execute the line Foo( AnotherClass.MyStaticData ); from the control ?

In your custom controls, you can check if they're in design mode or not and behave differently. For example, you can provide a default value instead of your missing static class property, so that the designer can render your desing-time control.

You have a lot of information about this in this page:

Custom Design-time Control Features in Visual Studio .NET

The property is ISite.DesigMode .

I answer myself, this is the solution :

Using ISite.DesignMode is apparently not working in a context of UserControl so I've found a reliable solution here : Detecting design mode from a Control's constructor

bool designMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);

Apparently, it is impossible to access the actual static data in the Designer. Thus, the only solution is to supply a dummy at design time. Combining the answers of 56ka and JotaBe, here is how to solve the problem:

public partial class MyControl : UserControl
{
    public MyControl()
    {
        InitializeComponent();
      
        if(LicenseManager.UsageMode == LicenseUsageMode.Designtime)
        {// Use a dummy value for display at design time.
            Foo(desginDummyValue); 
        }
        else
        {// Use the real static data only at runtime
            Foo( AnotherClass.MyStaticData ); 
        }
    }
}

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