【问题标题】:C# Preprocessor - Disabling Code for the XAML DesignerC# 预处理器 - 禁用 XAML 设计器的代码
【发布时间】:2011-08-29 16:29:42
【问题描述】:

不幸的是,我发现有时我正在编写的代码虽然在运行时非常好,但在使用 Visual Studio 2010 中的 XAML/Designer 时却让我头疼。我最喜欢的示例包括多个用于调试的 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; }
        }
    }

【问题讨论】:

标签: c# wpf silverlight visual-studio-2010 xaml


【解决方案1】:

您可以使用DesignerProperties.GetIsInDesignMode 方法,如下所示:

if (!DesignerProperties.GetIsInDesignMode(this) && _instance != null)
    throw new NotSupportedException(...)

【讨论】:

  • @Melodatron - 抱歉,没有预处理器指令,这不会真正起作用。假设您将 CustomFE 发送给其他开发人员以在他们的项目中使用。预处理器指令必须在编译时知道。使用上述方法,可以根据开发者的使用情况动态切换值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-29
  • 1970-01-01
  • 2021-11-21
相关资源
最近更新 更多