在企业级项目中,子窗口(ChildWindow)是一个常用控件,其展示方式是以弹出窗口来显示信息。 这里我将演示,子窗口传递参数到父窗口的方法。由于我的开发环境都是英文环境,所以部分中文可能显示不正常,请大家见谅。
我们的目的是希望用户在子窗口输入一串文字,然后点击提交后,字符串将被返回显示在父窗口。
1. 首先创建一个新项目 “SLChildWindow",
2. 然后在新项目中,右键点击添加,添加一个新项目,选择“子窗口”(ChildWindow), 改名为"ChildWindowDemo.xaml",添加完成后,在子窗口中添加一个文本框,名为 txtUserInfo,
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> 1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

3. 在子窗口后台代码中创建一个字符串类型的属性,该属性将用来保存用户输入的字符串,
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> 1

2

3

4

5 {
6
7 get {return testString;}
8
9 set { testString = value; }
10
11

12

4. 在子窗口中,建立一个EventHandler,父窗口将用该事件控制器获取子窗口参数,
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> 1

5. 当前,在子窗口有两个按钮,一个是Ok按钮,一个是Cancel按钮,后台有两个按钮事件OKButton_Click,CancelButton_Click; 在OKButton_Click中调用前面我们定义的时间控制器OkClicked,
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> 1

2 {
3 if (OkClicked != null)
4 {
5 TestString = txtUserInfor.Text;
6 OkClicked(this, new EventArgs());
7 }
8 this.DialogResult = true;
9 }
6. 在父窗口MainPage.xaml中建立一个子窗口的实例,方便父窗口调用子窗口,
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
-->

7. 在父窗口MainPage.xaml中调用子窗口的OkClicked事件,
Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/
--> 1

2 {
3 InitializeComponent();
4 childWindowDemo.OkClicked += new EventHandler(childWindowDemo_OkClicked);
5 }
6

7

8 {
9 tbInfo.Text = childWindowDemo.TestString;
10 }
11

12

13 {
14 childWindowDemo.Show();
15 }
16

8. 最后通过子窗口属性获取子窗口用户输入信息。
实例演示: http://silverlightchina.net/html/tips/2009/1125/261.html
代码下载: http://silverlightchina.net/uploads/soft/091125/1-091125163035.zip