WPF中是否有DesignMode属性?

107

在Winforms中,您可以这样说:

if ( DesignMode )
{
  // Do something that only happens on Design mode
}

WPF中是否有类似的东西?


2
请注意,GetIsInDesignMode方法存在与DesignMode属性相同的严重错误。 - BlueRaja - Danny Pflughoeft
5个回答

164

确实存在:

System.ComponentModel.DesignerProperties.GetIsInDesignMode

示例:

using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

public class MyUserControl : UserControl
{
    public MyUserControl()
    {
        if (DesignerProperties.GetIsInDesignMode(this))
        {
            // Design-mode specific functionality
        }
    }
}

我在我的应用程序中应用了您的解决方案,但它不起作用。 我在这里发问:http://stackoverflow.com/questions/3987439/init-grid-row-height-doesnt-work。 如果可以,请加入我们讨论。 - Nam G VU
@serhio 感谢您指出这一点。您知道有什么解决方法吗?顺便说一下,似乎在Silverlight中也不起作用:http://connect.microsoft.com/VisualStudio/feedback/details/371837/designerproperties-getisindesignmode-doesnt-work-with-silverlight-pages - Enrico Campidoglio
在VS2019中,必须启用“启用项目代码”开关(或菜单->设计->运行项目代码)。 - marbel82

48

在某些情况下,我需要知道我的非UI类是否是由设计师发起的调用(例如,如果我从XAML创建一个DataContext类)。 那么这个MSDN文章中的方法是有帮助的:

// Check for design mode. 
if ((bool)(DesignerProperties.IsInDesignModeProperty.GetMetadata(typeof(DependencyObject)).DefaultValue)) 
{
    //in Design mode
}

我在我的应用程序中尝试了您的解决方案,但它并没有起作用。我在这里提出了问题:http://stackoverflow.com/questions/3987439/init-grid-row-height-doesnt-work。如果可以的话,请加入我们讨论。 - Nam G VU

23

对于任何在WinForms中托管的WPF控件,DesignerProperties.GetIsInDesignMode(this)无法工作。

因此,我创建了Microsoft Connect中的一个错误并添加了一个解决方法:

public static bool IsInDesignMode()
{
    if ( System.Reflection.Assembly.GetExecutingAssembly().Location.Contains( "VisualStudio" ) )
    {
        return true;
    }
    return false;
}

应该使用GetEntryAssembly()而不是GetExecutingAssembly()吧?后者应该返回定义此属性的程序集。 - fjch1997

10

虽然我的回答有点晚,但是对于任何想在或XAML中使用此功能的人:

xmlns:componentModel="clr-namespace:System.ComponentModel;assembly=PresentationFramework"

<Style.Triggers>
    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, 
                 Path=(componentModel:DesignerProperties.IsInDesignMode)}" 
                 Value="True">
        <Setter Property="Visibility" Value="Visible"/>
    </DataTrigger>
</Style.Triggers>

-1
请使用这个:
if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
{
    //design only code here
}

(异步和文件操作在此处无法工作)

另外,在XAML中实例化设计时对象(d是特殊的设计器命名空间)

<Grid d:DataContext="{d:DesignInstance Type=local:MyViewModel, IsDesignTimeCreatable=True}">
...
</Grid>

1
那个类(Windows.ApplicationModel)是为商店应用程序设计的,包含在Windows Runtime API中。如果您只是在开发常规的Windows桌面应用程序,则这不是一个开箱即用的WPF解决方案。 - qJake

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接