WPF中是否有DesignMode属性?

Rus*_*uss 100 wpf .net-3.5

在Winforms中你可以说

if ( DesignMode )
{
  // Do something that only happens on Design mode
}
Run Code Online (Sandbox Code Playgroud)

在WPF中有这样的东西吗?

Enr*_*lio 150

确实有:

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果WPF托管在WinForm上,则此代码不起作用. (4认同)

Max*_*kin 47

在某些情况下,我需要知道,我的非UI类的调用是否由设计者启动(就像我从XAML创建一个DataContext类).然后,这篇MSDN文章的方法很有帮助:

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


ser*_*hio 20

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

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

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


Man*_*mer 5

我知道较晚的答案-但是对于其他想DataTrigger在XAML或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>
Run Code Online (Sandbox Code Playgroud)