在Winforms中,您可以这样说:
if ( DesignMode )
{
// Do something that only happens on Design mode
}
WPF中是否有类似的东西?
确实存在:
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
}
}
}
在某些情况下,我需要知道我的非UI类是否是由设计师发起的调用(例如,如果我从XAML创建一个DataContext类)。 那么这个MSDN文章中的方法是有帮助的:
// Check for design mode.
if ((bool)(DesignerProperties.IsInDesignModeProperty.GetMetadata(typeof(DependencyObject)).DefaultValue))
{
//in Design mode
}
对于任何在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虽然我的回答有点晚,但是对于任何想在或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>
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 Runtime API中。如果您只是在开发常规的Windows桌面应用程序,则这不是一个开箱即用的WPF解决方案。 - qJake