C# 预处理器 - 禁用 XAML 设计器中的代码

5

很遗憾,我发现有时我写的代码在运行时完全正常,但在使用Visual Studio 2010中的XAML/设计师时会引起麻烦。我的最爱的例子包括多个MessageBox用于调试出现,然而,当前的示例是构造函数中非常轻量级的单例式条件,这意味着当我想要在XAML中更改实例时,我必须重新构建解决方案。

是否有预处理器指令可用于跳过XAML设计器中的代码?

例:

    public class CustomFE : FrameworkElement
    {
        public CustomFE()
        {
#if !XAMLDesigner // Or something similar
            if (_instance != null)
                throw new NotSupportedException("Multiple instances not supported");
#endif

            _instance = this;
        }

        private static CustomFE _instance = null;

        public static CustomFE Instance
        {
            get { return _instance; }
        }
    }

请参见https://dev59.com/aXRC5IYBdhLWcg3wD8tV。 - Ian Ringrose
1个回答

4
您可以使用DesignerProperties.GetIsInDesignMode方法,如下所示:
if (!DesignerProperties.GetIsInDesignMode(this) && _instance != null)
    throw new NotSupportedException(...)

@Melodatron - 抱歉,没有预处理器指令,而且那也不会真正起作用。假设您将CustomFE交付给其他开发人员在其项目中使用。预处理器指令必须在编译时知道。使用上述方法,该值可以根据开发人员的使用动态切换。 - CodeNaked

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接