【问题标题】:Is there a DesignMode property in WPF?WPF 中是否有 DesignMode 属性?
【发布时间】:2010-09-30 08:36:24
【问题描述】:

在 Winforms 中你可以说

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

WPF 中有这样的东西吗?

【问题讨论】:

标签: wpf .net-3.5


【解决方案1】:

确实有

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
        }
    }
}

【讨论】:

【解决方案2】:

在某些情况下,我需要知道对我的非 UI 类的调用是否由设计器发起(例如,如果我从 XAML 创建 DataContext 类)。那么from this MSDN article 的方法很有帮助:

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

【讨论】:

【解决方案3】:

对于在 WinForms 中托管的任何 WPF 控件DesignerProperties.GetIsInDesignMode(this) 不起作用。

所以,我创建了a bug in Microsoft Connect 并添加了一个解决方法:

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

【讨论】:

  • 不应该是GetEntryAssembly()而不是GetExecutingAssembly()吗?后者应该返回定义此属性的程序集
【解决方案4】:

迟到的答案,我知道 - 但对于任何想在 DataTrigger 或一般 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>

【讨论】:

    【解决方案5】:

    使用这个:

    if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
    {
        //design only code here
    }
    

    (异步和文件操作在这里不起作用)

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

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

    【讨论】:

    • 该类 (Windows.ApplicationModel) 用于应用商店应用,包含在 Windows 运行时 API 中。如果您只是在使用常规 Windows 桌面应用程序,这不是一个开箱即用的 WPF 解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-06
    相关资源
    最近更新 更多