如何从一个用户控件传输或从其他用户control.cs获取值

时间:2018-05-08 04:54:13

标签: c# winforms

我想从这里转移价值

public partial class Burger : UserControl
{
    public int t_num_Z_bur = 0;
    public int t_num_B_bur = 0;
    mol md = new mol();

    private void button1_Click(object sender, EventArgs e)
    {
        t_num_Z_bur++;
        md.my(180);
        md.sou = "180";
        textBox1.Text = t_num_Z_bur.ToString();
    }

}

这是用户控制从这里我获取值并在文本框中进行更改1.如何更改值?

public partial class mol : UserControl
{
    public string sou
    {
        set { textBox1.Text = value; }
    }

    public void my (int value)
    {
        textBox1.Text = value.ToString();
    }
}

请帮帮我

提前致谢

1 个答案:

答案 0 :(得分:0)

处理容器之间通信的最佳方法是实现观察者类

观察者模式是一种软件设计模式,其中一个称为主体的对象维护其依赖者列表,称为观察者,并通常通过调用其中一种方法自动通知它们任何状态变化。 (维基百科)

我这样做的方法是创建一个Observer类,并在其中编写如下内容:

1    public delegate void dlFuncToBeImplemented(string signal);
2    public static event dlFuncToBeImplemented OnFuncToBeImplemented;
3    public static void FuncToBeImplemented(string signal)
4    {
5         OnFuncToBeImplemented(signal);
6    }

基本上如此:第一行表示会有其他人实施的功能

第二行是创建一个在委托函数调用时发生的事件

第三行是创建调用事件的函数

所以在你的UserControl中,你应该添加一个这样的函数:

private void ObserverRegister()//will contain all observer function registration
{
    Observer.OnFuncToBeImplemented += Observer_OnFuncToBeImplemented;
    /*and more observer function registration............*/
}


void Observer_OnFuncToBeImplemented(string signal)//the function that will occur when  FuncToBeImplemented(signal) will call 
{
    MessageBox.Show("Signal "+signal+" received!", "Atention!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}

并在您的表单中,您应该执行以下操作:

public static int signal = 0;

public void button1_Click(object sender, EventArgs e)
{
      Observer.FuncToBeImplemented(signal);//will call the event in the user control
}

现在,您可以将此功能注册到一大堆其他控件和容器中,它们都将获得信号

我希望这会有所帮助:)。