Visual Studio: "if (InDesigner)" Condition

This question touches me for a long time: Can I have a condition that is true if the Visual Studio designer fulfills 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 above this 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 fact that the elements are not visible in the visual 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; 
+6
source share
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 Blend or Visual Studio (I'm not sure which one 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 the current Application.Current program will always have your own derived application class (default: App defined in App.xaml and App.xaml.cs respectively)

+9
source

For a WPF application, you can try something like the following:

  if ((bool)(DesignerProperties.IsInDesignModeProperty.GetMetadata(typeof(DependencyObject)).DefaultValue)) { // If we're here it the design mode } 
+3
source

Source: https://habr.com/ru/post/906834/


All Articles