两种形式之间的沟通 [英] communicate between 2 forms

查看:96
本文介绍了两种形式之间的沟通的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的项目有2个对象:form1form2.

我停留在form1创建form2的1个对象.我停留在已初始化的form2时如何访问form1的属性和控件

my project has 2 object : form1, form2.

I stay at form1 create 1 object of form2. how do i access properties and controls of form1 while I''m staying at form2 which was initialized

推荐答案

这通常是通向意大利面条代码的路径.您的视觉设计师有充分的理由将这些控件设为私有.通常,您应该将该信息存储在业务对象中,而不仅是在UI层中,并进行绑定(正式使用.Net数据绑定机制,或者通过在初始化中设置属性来非正式地)绑定到业务对象,而不是在两种形式之间进行绑定.

我建议您阅读有关数据绑定的内容.即使您选择现在不将其用于您的项目,它也将在将来变得有用,并且您将更好地理解这些问题.

一个例外是模式对话框,例如选项表单或类似对话框.在这种情况下,属性在活动状态下无法更改,您可以在构造函数中进行设置,并在关闭后读取它们.例如:

This is generally the path to spaghetti code. Your visual designer makes those controls private for good reason. In general you should be storing that information in a business object, not just in the UI layer, and binding to it (either formally using the .Net data binding mechanism, or informally by setting properties in initialisation), not binding between two forms.

I recommend you read around data binding. Even if you choose not to use it for your project right now, it will come in useful in the future, and you will understand the issues much better.

One exception is a modal dialog, for example an options form or similar. In that case, the properties cannot change while it is active, and you can set them in the constructor and read them after dismissal. For example:

class Form1 {
 void OnSomeMenuItemClicked(MyOptionsClass options){
  OptionsForm optionsForm = new OptionsForm(options);
  if(DialogResult.OK == optionsForm.ShowDialog(this))
   optionsForm.SaveTo(options);
 }
}



MyOptionsClass只是一个数据类,OptionsForm在其构造函数(或Read方法)和SaveTo中对其进行读写.
与相同数据交互的两个无模式窗口不应直接设置彼此的控件.那就是疯狂.对于这种情况,.Net的数据绑定机制几乎可以肯定是正确的答案.



MyOptionsClass is just a data class and the OptionsForm reads and writes to it in its constructor (or a Read method) and SaveTo.

Two modeless windows interacting with the same data should not directly set each other''s controls. That way lies madness. For that scenario, .Net''s data binding mechanism is almost certainly the right answer.

class Form1 {
 void OnSomeOtherMenuItemClicked(){
  Form2 form2 = new Form2(dataSource);
  form2.Show(this);
}

class Form2 {
 Form2(object dataSource){
  this.CoolTextField.DataBindings.Add(''Text'', dataSource, ''CoolProperty'');
  // ... etc
 }


dataSource要么直接是您的业务对象,要么是覆盖它的绑定类,以便正确设置数据绑定所需的属性.


dataSource is either your business object directly, or a binding class that covers it so that the properties you need for data binding are set up correctly.


去那里看看如何在两个对象之间进行通信两种形式.
Link1- [两种形式之间的通信] [ Link2 [
Go there to take a look how to communicate between two form.
Link1-[Communication Between Two Forms][^]
Link2[^]


查看代表和事件.


这篇关于两种形式之间的沟通的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆