Search code examples
c#winformsuser-controlsdesigner

How to Correctly Reference Parent Form from UserControl


All, I have a UserCostrol which I have recently had to change. This changed required me to reference the Parent form and to use a property from this form. These references have seemingly broken the designer - I was getting an error

"Unable to cast object of type 'System.Windows.Forms.Form' to type 'Project.SettingsForm'"

which was discribed in Unable to cast object of type 'System.Windows.Forms.Form' to type 'Project.Form1'.

I have added a property to handle the reference to the Parent form as described in the answer refernced above, but now the designer error is saying

"Unable to cast object of type 'System.Windows.Forms.Panel' to type 'Project.SettingsForm'".

The first line which the compilier is moaning about is marked with '<-- Here' in the code below

public partial class UiSettingFascia : UserControl, ISettingsControl
{
    public UiSettingFascia()
    {
        InitializeComponent();
    }

    private void UiSettingFascia_Load(object sender, EventArgs e)
    {
        LoadSettings();
        CheckBoxShowTabs.CheckedChanged += Workbook_StateChanged;
        CheckBoxShowVirticalScroll.CheckedChanged += Workbook_StateChanged;
        CheckBoxShowHorizontolScroll.CheckedChanged += Workbook_StateChanged;
    }

    public void LoadSettings()
    {
        UserSettings userSettings = UserSettings.Instance();
        ...
        MainRibbonForm mainRibbonForm = (ControlParent).MainRibbonForm; // <-- Here.
        ...
    }
}

To attempt to fix the initial problem ["Unable to cast object of type 'System.Windows.Forms.Form' to type 'Project.SettingsForm'"] I have created the following property

public SettingsForm ControlParent
{
    get { return Parent as SettingsForm; }
}

How can I get around this problem ["Unable to cast object of type 'System.Windows.Forms.Panel' to type 'Project.SettingsForm'"] whilst maintaining my functionality of the UserControl?

Thanks for your time.


Solution

  • Add this extension method:

    public static class DesignTimeHelper
    {
        public static bool IsInDesignMode
        {
            get
            {
                bool isInDesignMode = (
                    LicenseManager.UsageMode == LicenseUsageMode.Designtime || 
                    Debugger.IsAttached == true);
                if (!isInDesignMode)
                {
                    using (var process = Process.GetCurrentProcess())
                    {
                        return process
                            .ProcessName.ToLowerInvariant()
                            .Contains("devenv");
                    }
                }
                return isInDesignMode;
            }
        }
    }
    

    Then, in your LoadSettings method:

    public void LoadSettings()
    {
        if (!DesignTimeHelper.IsInDesignMode)
        {
            var settingsForm = (SettingsForm)this.ParentForm;
        }
    }