如何:确定自定义控件处于设计时还是运行时

更新:2007 年 11 月

当您使用扩展性自定义 Visual Studio Windows Presentation Foundation (WPF) 设计器时,可能要自定义控件在设计时或运行时的行为。可为最终用户自定义设计时体验。例如,如果您创建一个自定义按钮,可以选择在设计时在按钮上显示文本,而不在运行时显示文本。您还可以自定义一个展示复杂行为的控件,以便该行为只有在运行时才会出现。例如,自动访问数据库的控件应在运行时访问数据库,而不在设计时访问数据库。

您可以通过调用 GetIsInDesignMode 方法来确定控件是在设计时运行还是在运行时运行。

使用设计模式属性

在本过程中,您在设计时在自定义按钮控件上显示文本,而不在运行时显示文本。

使用设计模式属性

  1. 在自定义控件的代码隐藏文件中,找到自定义控件的构造函数。

  2. 添加调用 GetIsInDesignMode 方法的代码,并相应地自定义控件的行为。将对自定义控件的引用作为一个参数传递给 GetIsInDesignMode,后者确定控件是否处于设计模式。例如,添加如下所示的代码:

    Namespace CustomControlLibrary
    
        Public Class ButtonWithDesignTime
            Inherits System.Windows.Controls.Button
    
            Public Sub New()
    
                If System.ComponentModel.DesignerProperties.GetIsInDesignMode(Me) Then
                    Me.Content = "This button is in design mode."
                End If
            End Sub
        End Class
    End Namespace
    
    namespace CustomControlLibrary
    {
        public class ButtonWithDesignTime : System.Windows.Controls.Button
        {
            public ButtonWithDesignTime()
            {
                if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
                {
                    this.Content = "This button is in design mode.";
                }
            }
        }
    }
    

请参见

其他资源

设计时与运行时行为

了解 WPF 设计器扩展性

WPF 设计器扩展性