开发者

Retrieve baseUri w/o resorting to Application.Current

My custom controls are not loading in VS.NET's designer because of a null reference exception. It's got everything to do with the way I am retrieving the baseUri of the application when it runs in the browser:

_uriPrefix = Application.Current.Host.Source.AbsoluteUri.Substring(0,
     Application.Current.Host.Source.AbsoluteUri.IndexOf("/ClientBin")).Trim();

According to the exception details and the help file I'm directed to (here) I'm not correctly designing my app for a runtime that's not the browser (i.e. the new WPF editor in VS.NET or Expression Blend). 开发者_StackOverflow社区

So, the question is how do retrieve the baseUri (the http://localhost:#### part of my application) if I can't use Application.Host which apparently is null during design time? is there a safe way to do this so I can load my custom controls in a designer?


To eleborate on the problem and solution (i wasn´t finished writing it when you posted your own answer)

Your problem is the runtime context you are in.

When your page is run as on a ASPX.Net page, your are hosted by the IIS->ASP.Net pipeline. This application will give your the HTTPContext and your Application.Current is refering to the W3WP.EXE process in which the ASP.Net pipeline is serving your page.

When your page is displayed in the MS Visual Studio designer it does not provide this HTTPContext since there is none. The request to render your control did not come through an HTTP request, but the Visual Studio designer running inside Visual Studio.

To have your control be displayed correctly during design time, you´ll have to add ´design time support classes´. There are a number in the .Net framework you can use directly, but for custom serialization (writing the server ASP.Net tags or rendering a HTML preview with styling) you´ll have to put in some more effort and write your own designer classes.

Hope this helps,


Duh! I hate/love when I do this. I'm answering my own question (again). I can use the DesignerProperties.IsInDesignTool boolean to test if I'm in design mode or not:

if (!DesignerProperties.IsInDesignTool)
     _uriPrefix = Application.Current.Host.Source.AbsoluteUri.Substring(0,
          Application.Current.Host.Source.AbsoluteUri.IndexOf("/ClientBin")).Trim();

Now I can view my custom control in the new VS 2010 editor. Yeah!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜