【发布时间】:2010-09-30 08:36:24
【问题描述】:
在 Winforms 中你可以说
if ( DesignMode )
{
// Do something that only happens on Design mode
}
WPF 中有这样的东西吗?
【问题讨论】:
-
请注意,GetIsInDesignMode 受 the same enormous bug as the DesignMode property 影响
在 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
}
}
}
【讨论】:
Enable project code 必须启用(或菜单->设计->?运行项目代码)。
在某些情况下,我需要知道对我的非 UI 类的调用是否由设计器发起(例如,如果我从 XAML 创建 DataContext 类)。那么from this MSDN article 的方法很有帮助:
// Check for design mode.
if ((bool)(DesignerProperties.IsInDesignModeProperty.GetMetadata(typeof(DependencyObject)).DefaultValue))
{
//in Design mode
}
【讨论】:
对于在 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()吗?后者应该返回定义此属性的程序集
迟到的答案,我知道 - 但对于任何想在 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>
【讨论】:
使用这个:
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 解决方案。