在静态方法中使用 WPF 检测设计模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12917566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detecting Design Mode using WPF in a Static Method
提问by Mashmagar
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.
我正在使用 WPF。我有一个静态类,它执行一些在设计模式下不可用的设置。此构造函数在设计模式下由窗口调用,从而导致抛出异常。
How do I detect design mode in a static method, so I can invoke the appropriate design mode behavior?
如何在静态方法中检测设计模式,以便调用适当的设计模式行为?
The recommended approachdoes 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).
静态构造函数是从 xaml 调用的,所以我不能有条件地调用它(除非我将调用移到代码隐藏,我想避免这种情况)。
In the window: <Window ... HelpProvider.Keyword="some_help_topic.html">
在窗口中: <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
}
采纳答案by Sergei B.
The possible way to solve it keeping attached property in xaml file is:
解决它在 xaml 文件中保留附加属性的可能方法是:
- 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.
- 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.
- 将初始化代码从静态构造函数移动到附加的属性更改回调。坦率地说,在静态构造函数中做这样的工作并不是很好的做法。
- 在您附加的属性更改回调中,您可以引用您的窗口。因此,您可以
DesignerProperties.GetIsInDesignMode(yourwindow)在那里致电并决定是否需要加载文件或任何导致问题的原因。

