Detecting Design Mode using WPF in a Static Method

穿精又带淫゛_ 提交于 2019-12-08 19:55:22

问题


I am using WPF. I have a static class that performs some setup not available during design mode. This constructor gets called by a window in design mode, which results in an exception being thrown.

How do I detect design mode in a static method, so I can invoke the appropriate design mode behavior?

The recommended approach does not work for static methods.


Edit:

The static constructor is called from xaml, so I can't conditionally call it (unless I move the call to code-behind, which I'd like to avoid).

In the window: <Window ... HelpProvider.Keyword="some_help_topic.html">

In the class:

static HelpProvider()
{
    // Load the .chm file from an application setting (this fails at design time)

    // Add a WPF command binding
}

回答1:


The possible way to solve it keeping attached property in xaml file is:

  1. Move initialization code from static constructor to attached property changed callback. Frankly speaking, it is not good practice to do such kind of work in static constructors.
  2. In your attached property changed callback you have a reference to your window. So you can call DesignerProperties.GetIsInDesignMode(yourwindow) there and decide, if you need to load file or whatever causes issues.


来源:https://stackoverflow.com/questions/12917566/detecting-design-mode-using-wpf-in-a-static-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!