无法转换类型为“System.Windows.Forms.Form”的对象输入“Project.Form1”

发布于 2024-11-03 12:37:33 字数 608 浏览 1 评论 0原文

我有一个 UserControl,它使用我的表单上可用的一些公共属性,位于此 UserControlPaint 事件的顶部,我引用控件的 Parent 并将其转换为我的表单的类型。

var _parent = (Form1)Parent;

但是,此代码可以工作,在“设计”视图中,会引发错误,并且我在 UserControl 处看到的只是一个白框,显示本文标题中的错误。堆栈跟踪直接指向这行代码。

现在,我已经通过用户控件中的属性重新路由此转换来修复此错误,

    public Form1 ControlParent
    {
        get
        {
            if (Parent != null)
            {
                return (Form1)Parent;
            }
            return null;
        }
    }

这对于破坏设计视图的东西来说有点太多了..还有其他想法吗?

I have a UserControl that uses some of the public properties that I have available on my Form, at the top of the Paint event for this UserControl, I reference the Parent of the control and cast it to the type of my Form.

var _parent = (Form1)Parent;

This code works however, in the Design view, an error is thrown and all I see in place of the UserControl is a white box displaying the error in the title of this post. The stacktrace leads directly to this line of code.

Right now, I have fixed this error by re-routing this cast through a Property in my UserControl

    public Form1 ControlParent
    {
        get
        {
            if (Parent != null)
            {
                return (Form1)Parent;
            }
            return null;
        }
    }

This is kind of a little much for something that just breaks the Design view.. any other ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

野心澎湃 2024-11-10 12:37:33

根据代码,您的子 Control 实例似乎已经可以处理 ControlParentnull 的情况。因此,最简单的修复方法就是执行以下操作

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

。 注意:一般来说,依赖于特定类型的 ControlParent 是一个坏主意。它可以防止它被重新托管在其他控件中,并且可能会破坏经常捏造类型以提供良好设计体验的设计人员。如果您必须依赖像 Parent 这样的特定类型的值,请确保有一个后备计划,该计划不会在面对不同类型时崩溃。

Based on the code it looks like your child Control instance can already deal with ControlParent being null. Hence the simplest fix would be to just do the following

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

Note: In general it's a bad idea to depend on the Parent of a Control being of a specific type. It prevents it from being re-hosted in other controls and can break designers which often fudge types around in order to provide a nice design experience. If you must depend on a value like Parent being of a specific type make sure to have a fall back plan which doesn't crash in the face of a different type.

一人独醉 2024-11-10 12:37:33

您是否检查了第一个代码中的parent 不为空?

Did you check that parent is not null in first code?

新雨望断虹 2024-11-10 12:37:33

您可以尝试设置表单的所有者,然后按照通过父属性尝试的方式访问该属性。

You can try by setting form's owner and then accessing that property the way you are trying through the parent property.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文