简体   繁体   English

c#Forms项目:将信息传递给用户控件

[英]c# Forms Project: Passing Information to User Control

I have created a forms application which uses a TabControl. 我创建了一个使用TabControl的窗体应用程序。 For each tab I want to place a single UserControl (created in the same project) which contains all the other controls. 对于每个选项卡,我想放置一个包含所有其他控件的UserControl(在同一项目中创建)。 However, I will need to pass some information from the primary form to the UserControl for it to work property with events, methods, etc. How can/should I do this? 但是,我将需要将一些信息从主表单传递给UserControl,以使其具有事件,方法等属性。我如何/应该这样做?

I tried creating a constructor with parameters but then Designer fails and I have to go in and delete out the added UserControl references. 我尝试使用参数创建构造函数,但随后Designer失败,因此我必须删除添加的UserControl引用。

Thanks! 谢谢!

The constructor parameter is the correct method. 构造函数参数是正确的方法。 However, there must still be a default constructor in order for the Designer to be able to construct (and draw) a copy of the object. 但是,仍然必须有一个默认的构造函数,以便Designer能够构造(和绘制)对象的副本。

My usual workaround is to put a clause in the default constructor, checking to see that we are in "design mode" and throwing an exception if not: 我通常的解决方法是在默认构造函数中放置一个子句,检查是否处于“设计模式”,如果不是,则抛出异常:

public class MyForm: Form
{
   public MyForm()
   {
      if(!DesignMode) throw new InvalidOperationException("Cannot use default constructor in production code");
   }

   public MyForm(MyDependency dependent)
   {
      ...
   }
}

you can pass information by a function that created in usercontrol.cs file. 您可以通过在usercontrol.cs文件中创建的函数传递信息。

for example in usercontrol.cs 例如在usercontrol.cs中

public string name;
public void SetName(string pname)
{
this.name = pname;
} 

or maybe you want to change button name 或您想更改按钮名称

Button mybutton = new Button();
public void SetButtonName(string btname)
{
this.mybutton.Text = btname;
}

Now you can call these functions in your mainform.cs 现在您可以在mainform.cs中调用这些函数

Myusercontrol usc = new Myusercontrol();
usc.SetName("this is string for 'name' string");
usc.SetButtonName("this is string for button text");

Try creating your constructor, but also creating a default parameterless constructor. 尝试创建构造函数,但还要创建默认的无参数构造函数。

Take a look at this question 看看这个问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM