开发者

WPF Designer ONLY: NullReferenceException when loading connection string from app.config

Please help, for the sake of my non-pulled out hair...

The following code line:

this._connectionString = ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString;

is causing me untold amounts of grief.

It is in a user control, currently in the control's Loaded event but I've also tried the constructor and just plain initializing th开发者_如何学Ce field to the value when it's declared. Whenever I do so, the WPF designer pitches a fit on any screen that uses said user control.

The code itself compiles fine, and runs with no issues. But it's turning into a real hampering in development not being able to use the designer at all. Does anyone have any clue what could cause this and a hint as to a good practice to avoid it in the future? I suspect it has something to do with trying to access the ConfigurationManager but I can't figure out where to put the line to make it stop.

Thanks.

PS: Visual Studio 2010 Premium


When you're working in design time, you should avoid loading this. Fill in the value with some other, appropriate default, instead:

if (DesignerProperties.GetIsInDesignMode(this))
    this._connectionString = "Default";
else
{
    this._connectionString = ConfigurationManager
                              .ConnectionStrings["SqlConnectionString"]
                              .ConnectionString;
}


The designer probably isn't looking at your app's configuration but rather at the configuration of its current host app (VS), and so ConfigurationManager.ConnectionStrings["SqlConnectionString"] returns null at design-time.


This restriction is similar to what is see in MVC applications whereby the Web.Config doesn't get instantiated at design time. Lo...WPF does the same thing whereby the App.Config is not present at design time.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜