【问题标题】:C# - How to Transfer Information Between User ControlC# - 如何在用户控件之间传输信息
【发布时间】:2013-01-27 05:26:24
【问题描述】:

我正在做一个应用程序,用户在文本框中输入一个值,然后他按下一个按钮,两者都在同一个用户控件中。然后文本框的结果将显示在其他用户控件的标签上。两个用户控件都在同一个窗体中。

谢谢!

Image of user interface

【问题讨论】:

  • 请提供您的一些代码,以便我们了解您必须开始什么
  • 还有 - 这是 WPF 还是 windows 窗体?
  • 您使用的是什么 UI 设计模式。您的控制器应该能够通过更新其依赖属性来触发标签更新。
  • 我是新来的...@theodox ...我使用 Windows 窗体

标签: c# winforms


【解决方案1】:

最常见的方法是使用事件。我会这样做:

首先定义一个EventArgs:

public class MyEventArgs : EventArgs
{
    public string Text { get; private set; }

    public MyEventArgs(string Text)
    {
        this.Text = Text;
    }
}

然后在您的 UserControl(带有按钮的那个)中:

public partial class MyUserControl
{
    public event EventHandler<MyEventArgs> ButtonClicked;

    public MyUserControl()
    {
        //...

        button1.Click += (o, e) => OnButtonClicked(new MyEventArgs(textBox1.Text));
    }

    protected virtual void OnButtonClicked(MyEventArgs args)
    {
        var hand = ButtonClicked;
        if(hand != null) ButtonClicked(this, args);
    }
}

然后在表单中订阅你的MyUserControl.ButtonClicked事件并调用第二个控件中的方法。


请注意,如果按钮的行为和文本框中的文本实际上相关,您可以使用属性来获取输入的文本,并为您的事件使用一个空的EventArgs

附:名称MyEventArgsMyUserControlButtonClicked 仅用于演示目的。我鼓励您在代码中使用更具描述性/相关性的命名。

【讨论】:

    【解决方案2】:

    试试这个:

    public class FirstUserControl:UserControl
    {
        Public event EventHandler MyEvent;
    
        //Public property in your first usercontrol
        public string MyText
        {
            get{return this.textbox1.Text;} //textbox1 is the name of your textbox
        }
    
        private void MyButton_Clicked(/* args */)
        {
            if (MyEvent!=null)
            {
                MyEvent(null, null);
            }
        }
        //other codes
    }
    
    
    public class SecondUserControl:UserControl
    {
        //Public property in your first usercontrol
        public string MyText
        {
            set{this.label1.Text = value;} //label1 is the name of your label
        }
    
        //other codes
    }
    

    然后在您的 MainForm 中:

    public class MainForm:Forms
    {
        //Add two instance of the UserControls
    
        public MainForm()
        {
            this.firstUserControl.MyEvent += MainWindow_myevent;
        }
    
        void MainWindow_myevent(object sender, EventArgs e)
        {
            this.secondUserControl.MyText = this.firstUserControl.MyText;
        }
    
        //other codes
    }
    

    【讨论】:

      猜你喜欢
      • 2019-11-25
      • 1970-01-01
      • 2021-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多