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;
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)
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With