-
06-09-2019 - |
문제
이전에 기본 생성자를 사용했던 C#에서 만든 구성 요소가 있지만 이제는 부모 양식이 자체에 대한 참조를 전달하여 객체 (디자이너에서)를 만들기를 원합니다.
다시 말해, 디자이너의 다음 대신 CS :
this.componentInstance = new MyControls.MyComponent();
양식 디자이너에게 다음을 만들도록 지시하고 싶습니다.
this.componentInstance = new MyControls.MyComponent(this);
이를 달성 할 수 있습니까 (바람직하게는 일부 속성/주석을 통해)?
해결책
당신은 단순히 사용할 수 없습니다 Control.parent 재산? 물론, 그것은 당신의 컨트롤의 생성자에 설정되지 않지만 그것을 극복하는 일반적인 방법은 구현에 의한 것입니다. isupportinitialize 그리고 작업을 수행합니다 엔디니트 방법.
왜 Oring Control에 대한 참조가 필요한가?
여기에서 새 콘솔 애플리케이션을 작성 하고이 콘텐츠에 붙여 넣기 위해 Program.cs의 내용을 대체하고 실행하면 .endinit,, 부모의 속성이 올바르게 설정됩니다.
using System;
using System.Windows.Forms;
using System.ComponentModel;
using System.Drawing;
namespace ConsoleApplication9
{
public class Form1 : Form
{
private UserControl1 uc1;
public Form1()
{
uc1 = new UserControl1();
uc1.BeginInit();
uc1.Location = new Point(8, 8);
Controls.Add(uc1);
uc1.EndInit();
}
}
public class UserControl1 : UserControl, ISupportInitialize
{
public UserControl1()
{
Console.Out.WriteLine("Parent in constructor: " + Parent);
}
public void BeginInit()
{
Console.Out.WriteLine("Parent in BeginInit: " + Parent);
}
public void EndInit()
{
Console.Out.WriteLine("Parent in EndInit: " + Parent);
}
}
class Program
{
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
}
}
다른 팁
디자이너가 실제로 비 디펜트 생성자를 호출하는 디자이너 방출 코드가있는 방법을 모르겠지만 여기에 주변을 돌아 다니는 아이디어가 있습니다. 초기화 코드를 부모 양식의 기본 생성자 안에 넣고 양식을 사용하여 실행 해야하는지 확인하십시오.
public class MyParent : Form
{
object component;
MyParent()
{
if (this.DesignMode)
{
this.component = new MyComponent(this);
}
}
}
제휴하지 않습니다 StackOverflow