1

所有,我有一个UserCostrol我最近不得不改变的。这种变化要求我引用Parent表单并使用该表单中的属性。这些参考资料似乎破坏了设计师 - 我遇到了一个错误

“无法将'System.Windows.Forms.Form'类型的对象转换为'Project.SettingsForm'”

这在Unable to cast object of type 'System.Windows.Forms.Form' to type 'Project.Form1' 中有所描述。

我已经添加了一个属性来处理对Parent表单的引用,如上面引用的答案中所述,但现在设计器错误说

“无法将'System.Windows.Forms.Panel'类型的对象转换为'Project.SettingsForm'”。

编译器抱怨的第一行在'<-- Here'下面的代码中标有

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.
        ...
    }
}

为了尝试解决最初的问题 [ “无法将 'System.Windows.Forms.Form' 类型的对象转换为 'Project.SettingsForm'” ] 我创建了以下属性

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

我怎样才能解决这个问题[ “无法将'System.Windows.Forms.Panel'类型的对象转换为'Project.SettingsForm'” ]同时保持我的功能UserControl

谢谢你的时间。

4

2 回答 2

1

看起来您需要编写一些设计时行为。在设计时,UserControl 的父级实际上可能是 Visual Studio(或其某些组件)。这就是 Visual Studio 能够为您提供在设计时使用控件的 GUI 的方式——它实际上是控件的宿主;它实际上正在执行。

您可能需要在采用父表单的属性上设置一个属性,以便在设计时为其提供一些其他行为。另外,我认为 UserControls 上有一个属性,DesignMode当控件处于设计模式时,它会为真——这样,您可以在设计时和运行时赋予控件不同的行为。MSDN 上有很多关于创建控件和配置它们的设计时与运行时行为的文章。

于 2013-07-24T12:55:44.747 回答
1

添加此扩展方法

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;
        }
    }
}

然后,在您的LoadSettings方法中:

public void LoadSettings()
{
    if (!DesignTimeHelper.IsInDesignMode)
    {
        var settingsForm = (SettingsForm)this.ParentForm;
    }
}
于 2013-07-24T13:52:23.860 回答