2011-05-20 101 views
5

不幸的是,我發現有時候我正在編寫的代碼在運行時非常好,在使用Visual Studio 2010中的XAML/Designer時會讓我頭疼。示例包括用於調試的多個MessageBoxes,但是,當前示例在構造函數中是一個非常輕的Singleton樣式條件,這意味着當我想更改XAML中的實例時,必須重新構建解決方案。C#預處理器 - 禁用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; } 
     } 
    } 
+0

也看到http://stackoverflow.com/questions/425760/is-there-a-designmode -property-in-wpf – 2011-05-20 13:47:45

回答

4

可以使用DesignerProperties.GetIsInDesignMode方法,像這樣:

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

真的嗎?有沒有預處理它? 這有點糟糕... – Melodatron 2011-05-20 13:47:32

+0

@Melodatron - 對不起,沒有預處理指令,這不會真的工作。假設您將CustomFE發送給其他開發人員以供他們的項目使用。編譯時必須知道預處理器指令。使用上述方法,可以根據開發人員如何使用它來動態切換該值。 – CodeNaked 2011-05-20 14:20:10