Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Preprocessor - Disabling Code for the XAML Designer

Unfortunately I've found that sometimes code I'm writing, while perfectly fine at run-time, causes me headaches when working with the XAML/Designer in Visual Studio 2010. My favourite examples includes multiple MessageBoxes for debugging appearing, however, the current example is a very light Singleton-style condition in the constructor that means I have to rebuild the solution when I want to make changes to the instance in the XAML.

Is there a preprocessor directive that I can use to skip over code in the XAML Designer?

Example:

    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; }
        }
    }
like image 369
Melodatron Avatar asked Oct 12 '22 00:10

Melodatron


1 Answers

You can use the DesignerProperties.GetIsInDesignMode method, like so:

if (!DesignerProperties.GetIsInDesignMode(this) && _instance != null)
    throw new NotSupportedException(...)
like image 165
CodeNaked Avatar answered Nov 04 '22 12:11

CodeNaked