28 July 2010

User Control Design Time Detection

Today, I created a wizard application in WPF/C#.  Each "page" of the wizard is a user control.  Each user control is largely autonomous, each having a pointer to a singleton instance DataManager class that persists data between the controls and parent window.  When a control is made visible, it checks the values of the DataManager class, to ensure the requisite values are available, etc.

The "page" controls are not instantiated on-demand, for reasons I will not discuss here.  When viewing the main window in the WPF designer, all of the user controls that perform data verification in their IsVisibleChanged event handler cause the WPF designer rendering to fail, although I did get several MessageBoxes containing the various validation error messages.  (At least I know those work well!)

The solution is to wrap all validation logic in an IF statement that checks to see if the control is being rendered in a designer.  It we are indeed in design time, the validation logic is stepped over.

private void UserControl_IsVisibleChanged(
    object sender, 
    DependencyPropertyChangedEventArgs e)
{
    if (DesignerProperties.GetIsInDesignMode(this)
        || this.Visibility != Visibility.Visible)
        return;

    // Validation logic here...
}

No comments:

Post a Comment

Please provide details, when posting technical comments. If you find an error in sample code or have found bad information/misinformation in a post, please e-mail me details, so I can make corrections as quickly as possible.