WPF 中是否有 DesignMode 属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/425760/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a DesignMode property in WPF?
提问by Russ
In Winforms you can say
在 Winforms 中,您可以说
if ( DesignMode )
{
// Do something that only happens on Design mode
}
is there something like this in WPF?
WPF中有这样的东西吗?
回答by Enrico Campidoglio
Indeed there is:
确实有:
System.ComponentModel.DesignerProperties.GetIsInDesignMode
System.ComponentModel.DesignerProperties.GetIsInDesignMode
Example:
例子:
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
public class MyUserControl : UserControl
{
public MyUserControl()
{
if (DesignerProperties.GetIsInDesignMode(this))
{
// Design-mode specific functionality
}
}
}
回答by Max Galkin
In some cases I need to know, whether a call to my non-UI class is initiated by the designer (like if I create a DataContext class from XAML). Then the approach from this MSDN articleis helpful:
在某些情况下,我需要知道对我的非 UI 类的调用是否由设计器发起(就像我从 XAML 创建 DataContext 类一样)。那么这篇 MSDN 文章中的方法很有帮助:
// Check for design mode.
if ((bool)(DesignerProperties.IsInDesignModeProperty.GetMetadata(typeof(DependencyObject)).DefaultValue))
{
//in Design mode
}
回答by serhio
For any WPF Controls hosted in WinForms, DesignerProperties.GetIsInDesignMode(this)
does not work.
对于WinForms 中托管的任何 WPF 控件,DesignerProperties.GetIsInDesignMode(this)
都不起作用。
So, I created a bug in Microsoft Connectand added a workaround:
因此,我在 Microsoft Connect 中创建了一个错误并添加了一个解决方法:
public static bool IsInDesignMode()
{
if ( System.Reflection.Assembly.GetExecutingAssembly().Location.Contains( "VisualStudio" ) )
{
return true;
}
return false;
}
回答by Manfred Radlwimmer
Late answer, I know - but for anyone else who wants to use this in a DataTrigger
, or anywhere in XAML in general:
迟到的答案,我知道 - 但对于任何想要DataTrigger
在 .
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>
回答by Jeson Martajaya
Use this one:
使用这个:
if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
{
//design only code here
}
(Async and File operations wont work here)
(异步和文件操作在这里不起作用)
Also, to instantiate a design-time object in XAML (d is the special designer namespace)
此外,在 XAML 中实例化设计时对象(d 是特殊的设计器命名空间)
<Grid d:DataContext="{d:DesignInstance Type=local:MyViewModel, IsDesignTimeCreatable=True}">
...
</Grid>