5

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; }
        }
    }
Melodatron
  • 610
  • 4
  • 10

1 Answers1

4

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

if (!DesignerProperties.GetIsInDesignMode(this) && _instance != null)
    throw new NotSupportedException(...)
CodeNaked
  • 40,753
  • 6
  • 122
  • 148
  • @Melodatron - Sorry, no preprocessor directive and that wouldn't really work. Let's assume you ship CustomFE to other devs for use in their projects. The preprocessor directive has to be known at compile time. Using the method above, the value can be dynamically switched based on how the devs are using it. – CodeNaked May 20 '11 at 14:20