点击A中button打开B,且取值并传值给B里面的方法。其中B是单例模式的用户控件。试了委托,每次调用时委托方法都判断为null,无法调用B里面的方法。急求解决方法或代码!!!!感谢。
B构造函数中的A和其他方法添加到form中的A是不同的实例,其他方式添加的A实例的search是没有赋值的。除非你正在操作的A是通过B构造函数中实例化后添加到form中的A
其实题主的单实例模式没写对。,单实例实现是要隐藏构造函数的,将构造函数改为private,只能通过instance属性来访问,添加B控件也只能通过代码来添加instance到form中。
需要注意构造函数private后,工具箱还是可以拖拽到form上,而且可以拖动多个,但是编译的时候会报错,构造函数隐藏了导致对应控件为null。
如果为单实例模式,就不需要search了,直接B.Instance.Func()调用搞定。。。有帮助或启发麻烦点个采纳【本回答右上角】,谢谢~~有其他问题可以继续交流~
示例代码如下
Form1.cs
private void Form1_Load(object sender, EventArgs e)
{
this.Controls.Add(B.Instance);
B.Instance.Location = new Point(300, 10);
this.Controls.Add(B.Instance);//这句无效,同一个实例,所以不会出现2个
B.Instance.Location = new Point(300, 100);
}
B.cs
using System;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class B : UserControl
{
private static B _instance = null;
public static B Instance
{
get
{
if (_instance == null || _instance.IsDisposed)
{
_instance = new B();
}
return _instance;
}
}
public void Func()
{
textBox1.Text = DateTime.Now.ToString();
}
private B()//私有构造函数,不对外
{
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}
}
}
A.cs
using System;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class A : UserControl
{
public A()
{
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe);
}
private void button1_Click(object sender, EventArgs e)
{
if (!B.Instance.Visible)
{
B.Instance.Show();
}
else B.Instance.Func();
}
}
}
有没有具体代码。