C# 如何不使用UserControl.dispose()
在这种情况下,用户单击UserControl的X,如果存在某个条件,我希望继续显示用户控件。我原以为调用C# 如何不使用UserControl.dispose(),c#,winforms,C#,Winforms,在这种情况下,用户单击UserControl的X,如果存在某个条件,我希望继续显示用户控件。我原以为调用base.Dispose(false)就可以了,但事实并非如此。 我该怎么做 FeatureView.Designer.cs partial class FeatureView { // User clicked the X on the control protected override void Dispose(bool disposing) {
base.Dispose(false)
就可以了,但事实并非如此。
我该怎么做
FeatureView.Designer.cs
partial class FeatureView
{
// User clicked the X on the control
protected override void Dispose(bool disposing)
{
// Note: base.GetType() = FeatureView
if (someCondition) // then dispose
{
base.Dispose(true);
}
else // keep displaying the Feature, do not dispose
{
base.Dispose(false); // nope
}
}
}
FeatureView.cs
public partial class FeatureView : System.Windows.Forms.UserControl
{
}
用户控件必须嵌入到窗体中才能可见。在form lvel中,您可以捕获FormClosing事件并将cancel设置为true
this.FormClosing += Form_ManageFavorites_FormClosing;
private void Form_ManageFavorites_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
}
用户控件必须嵌入到窗体中才能可见。在form lvel中,您可以捕获FormClosing事件并将cancel设置为true
this.FormClosing += Form_ManageFavorites_FormClosing;
private void Form_ManageFavorites_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = true;
}
最好不要将自定义代码放在.Designer.cs文件中,而是使用常规的.cs文件。X是在用户控件本身中还是在表单中?大多数程序员这样做是偶然的,这是很难诊断泄漏的一个常见原因。使用父控件的Controls.Remove()方法,当您关闭表单时,它将不会被释放。保留对它的引用,以便可以将其添加回新表单实例,并在必要时进行处置,这一点非常重要。而且实现起来并不明显,可能需要一个静态变量。显示用户按下此“X”功能时运行的代码。UserControl没有X。那么您的控件如何有X?最好不要将自定义代码放在.Designer.cs文件中,改为使用常规的.cs文件。X是在用户控件本身还是表单中?大多数程序员这样做是偶然的,这是很难诊断泄漏的一个常见原因。使用父控件的Controls.Remove()方法,当您关闭表单时,它将不会被释放。保留对它的引用,以便可以将其添加回新表单实例,并在必要时进行处置,这一点非常重要。而且实现起来并不明显,可能需要一个静态变量。显示当用户按下你的“X”功能时你运行的代码。UserControl没有X。那么你的控件怎么会有X呢?谢谢你的回复。有些不对劲,不确定是什么
this.FormClosing()
不存在this.FindForm()
返回null。感谢您的回复。有些不对劲,不确定是什么this.FormClosing()
不存在this.FindForm()
返回null。