如何解决在C#Form应用程序的用户控件之间传递数据
我有两个用户控件。由于某些原因,我不想单击并将它们拖到“表单”中。因此,我在“表单加载”期间将它们加载到表单中的面板(mainPanel)上,然后通过单击按钮将所需的表单带到前面。我将在ucFirst的文本框中输入一些数据。我想做的是通过在ucFirst中按下按钮将此值传递到ucSecond的文本框中。我正在尝试活动。但是我该如何在ucFirst中访问ucSecond的文本框,并用ucFirst用户的文本重新加载ucSecond
//Form.cs
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private static Form1 _obj;
public static Form1 Instance
{
get
{
if (_obj == null)
_obj = new Form1();
return _obj;
}
}
private void Form1_Load(object sender,EventArgs e)
{
_obj = this;
//create first user control instance
UC_1 ucFirst = new UC_1();
ucFirst.Dock = DockStyle.Fill;
Form1.Instance.mainPanel.Controls.Add(ucFirst);
//create second user control instance
UC_2 ucSecond = new UC_2();
ucSecond.Dock = DockStyle.Fill;
Form1.Instance.mainPanel.Controls.Add(ucSecond);
//Subscribe to events
ucFirst.TextEntered += TextAvailableFromUcFirst;
}
private void TextAvailableFromUcFirst(object sender,string availableText)
{
UC_1 ucFirst = sender as UC_1;
//How do I use the text in ucSecond ????
//ucSecond.textBoxUcSecond.Text = availableText;
}
private void showFirstUcBtn_Click(object sender,EventArgs e)
{
Form1.Instance.mainPanel.Controls["UC_1"].BringToFront();
}
}
//UC_1.cs
public delegate void TextEventHandler(object sender,string text);
public partial class UC_1 : UserControl
{
private static UC_1 _instance;
public static UC_1 Instance
{
get
{
if (_instance == null)
_instance = new UC_1();
return _instance;
}
}
public UC_1()
{
InitializeComponent();
}
private void UC_1_Load(object sender,EventArgs e)
{
_instance = this;
}
//Create an event
public event TextEventHandler TextEntered;
protected virtual void OnTextEntered(string text)
{
TextEntered?.Invoke(this,text);
}
private void firstUcBtn_Click(object sender,EventArgs e)
{
//raise the event on button click
//passing the text entered on text box
string textBoxText = textBoxUcFirst.Text;
OnTextEntered(textBoxText);
//I need to show the text in ucSecond textbox,but how ???
Form1.Instance.mainPanel.Controls["UC_2"].BringToFront();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。