대리인과 이벤트를 사용하여 Windows Forms 양식 간에 변수 전달
이 시나리오에서는 기본 양식과 "설정" 하위 항목이 있습니다. form에서 변수를 자식 폼에 전달하는 일반적인 접근 방식은 대리자를 사용하는 것입니다. events.
1단계: 대리인 및 이벤트 초기화
기본 양식에서 데이터 전송을 처리할 대리인과 이벤트를 생성합니다.
public partial class MainForm : Form { /// <summary> /// Delegate to send data between forms /// </summary> public delegate void PageInfoHandler(object sender, PageInfoEventArgs e); /// <summary> /// Event of the delegate /// </summary> public event PageInfoHandler PageInfoRetrieved; }
2단계: 이벤트에 변수 전달 핸들러
기본 양식에서 "설정" 버튼을 클릭하면 전달하려는 변수로 이벤트 인수 인스턴스를 생성하고 이벤트를 발생시킵니다.
private void toolStripBtnSettings_Click(object sender, EventArgs e) { PageInfoEventArgs args = new PageInfoEventArgs(SomeString); this.OnPageInfoRetrieved(args); SettingsForm settingsForm = new SettingsForm(); settingsForm.ShowDialog(); }
3단계: 하위 양식에서 변수 검색
"설정" 양식에서 해당 이벤트 핸들러를 재정의하여 이벤트를 생성합니다.
public partial class SettingsForm : Form { protected override void OnShown(EventArgs e) { base.OnShown(e); // Retrieve the event arguments PageInfoEventArgs args = this.Tag as PageInfoEventArgs; if (args != null) { // Access the passed variable string receivedText = args.PageInfo; } } }
생성자를 사용하여 변수 전달
또는 변수를 자식 생성자에 직접 전달할 수도 있습니다. form:
public partial class SettingsForm : Form { private string receivedText; public SettingsForm(string text) { this.receivedText = text; } }
이 경우 변수를 사용하여 하위 양식 인스턴스를 생성합니다. 인수:
SettingsForm settingsForm = new SettingsForm(SomeString);
위 내용은 대리인과 이벤트 또는 생성자를 사용하여 Windows Forms 간에 변수를 전달하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!