[英]How to Correctly Reference Parent Form from UserControl
所有人,我有一个UserCostrol
,最近我不得不对其进行更改。 更改后,我需要引用“ Parent
表单并使用该表单中的属性。 这些参考资料似乎破坏了设计师-我遇到了错误
“无法将类型为'System.Windows.Forms.Form'的对象转换为类型为'Project.SettingsForm'的对象”
在无法将类型为System.Windows.Forms.Form的对象转换为类型Project.Form1中进行了描述 。
我已经添加了一个属性来处理对Parent
窗体的引用,如上面引用的答案中所述,但是现在设计器错误是在说
“无法将类型为'System.Windows.Forms.Panel'的对象转换为类型为'Project.SettingsForm'的对象”。
编译器抱怨的第一行在'<-- Here'
的代码中标记为'<-- Here'
-Here '<-- 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
功能?
谢谢你的时间。
看起来您需要在某些设计时行为中进行编码。 在设计时,UserControl的父控件实际上可以是Visual Studio(或其某些组件)。 这就是Visual Studio能够为您提供在设计时使用该控件的GUI的方式-它实际上是托管控件的对象。 它实际上正在执行。
您可能需要在该属性上设置一个属性,该属性采用父窗体,以在设计时赋予其其他行为。 另外,我认为UserControls上有一个名为DesignMode
的属性,当控件处于设计模式时该属性将为true –这样,您可以在设计时与运行时为控件赋予不同的行为。 MSDN上有很多关于创建控件和配置控件设计时与运行时行为的文章。
添加此扩展方法 :
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.