Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Visual Studio: Condition "if (InDesigner)"

This question bugs me since a long time: Can I have a condition that is true if the Visual Studio designer is executing it, and false otherwise?

For example (WPF), I want to use a special BoolToVisibilityConverter to bind the visibility property of some controls to the mouse being over that control. I do this with the following XAML code:

<Image Width="50" Height="50" Source="../Images/MB_0010_tasks.ico" Margin="12,133,133,12" MouseLeftButtonUp="Image_MouseLeftButtonUp" 
          Visibility="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}, Path=IsMouseOver, Converter={StaticResource __boolToVisibilityConverter}}" />

This leads to the elements not being visible in Visual Studio's designer view. Is there a way to tell the Converter something like this:

#if DESIGNER
return Visibility.Visible;
#endif
return b ? Visibility.Visible : Visibility.Hidden;
like image 875
Akku Avatar asked Jan 25 '12 10:01

Akku


2 Answers

You can use the System.ComponentModel.DesignerProperties.GetIsInDesignMode() method:

// In WPF:
var isDesign = DesignerProperties.GetIsInDesignMode(Application.Current.MainWindow);

// In Silverlight:
var isDesign = DesignerProperties.GetIsInDesignMode(Application.Current.RootVisual);

if(isDesign)
{
    // designer code
    return;
}

// non designer code

In either Blend or Visual Studio (I'm not sure which one it was) this will always be false, so you should also include the following check:

isDesign = isDesign || Application.Current.GetType().Equals(typeof(Application));

This works because in the running program Application.Current will always be your own derived Application class (by default: App, defined in App.xaml and App.xaml.cs respectively)

like image 66
Nuffin Avatar answered Sep 17 '22 23:09

Nuffin


For a WPF application you could try something like the following:

        if ((bool)(DesignerProperties.IsInDesignModeProperty.GetMetadata(typeof(DependencyObject)).DefaultValue))
        {
            // If we're here it's the design mode
        }
like image 42
ken2k Avatar answered Sep 17 '22 23:09

ken2k