无法转换类型为“System.Windows.Forms.Form”的对象输入“Project.Form1”
我有一个 UserControl
,它使用我的表单上可用的一些公共属性,位于此 UserControl
的 Paint
事件的顶部,我引用控件的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
根据代码,您的子
Control
实例似乎已经可以处理ControlParent
为null
的情况。因此,最简单的修复方法就是执行以下操作。 注意:一般来说,依赖于特定类型的
Control
的Parent
是一个坏主意。它可以防止它被重新托管在其他控件中,并且可能会破坏经常捏造类型以提供良好设计体验的设计人员。如果您必须依赖像Parent
这样的特定类型的值,请确保有一个后备计划,该计划不会在面对不同类型时崩溃。Based on the code it looks like your child
Control
instance can already deal withControlParent
beingnull
. Hence the simplest fix would be to just do the followingNote: In general it's a bad idea to depend on the
Parent
of aControl
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 likeParent
being of a specific type make sure to have a fall back plan which doesn't crash in the face of a different type.您是否检查了第一个代码中的parent 不为空?
Did you check that parent is not null in first code?
您可以尝试设置表单的所有者,然后按照通过父属性尝试的方式访问该属性。
You can try by setting form's owner and then accessing that property the way you are trying through the parent property.