上一章中,对Shell, Region, View有了一个初步的了解。我们可以通过这些类向指定的用户控件加载Shell中,但是目前,还无法实现模块之间的交互。接下来开始开始逐步探索这方面的应用。
还是继续上一章中的例程接着往下改。在Prism中,允许在UI中绑定Command对象来实现MVVM模式。步聚如下:
1. 在InterfaceProject模块中的ITextServices中修改代码,如下:
1
public
interface ITextService
2 {
3 string GetText();
4 void SetText( string newText);
5
6 event EventHandler TextChanged;
7 }
2 {
3 string GetText();
4 void SetText( string newText);
5
6 event EventHandler TextChanged;
7 }
2.在ModuleAProject项目的Services文件夹下,修改TextService.cs中的代码,如下:
1
public
class TextService:ITextService
2 {
3 public TextService()
4 {
5 text = " Hello Silverlight! ";
6 }
7 public string GetText()
8 {
9 return text;
10 }
11 public void SetText( string newText)
12 {
13 this.text = newText;
14
15 if (TextChanged != null)
16 {
17 TextChanged( this, EventArgs.Empty);
18 }
19 }
20
21 string text;
22 public event EventHandler TextChanged;
23 }
2 {
3 public TextService()
4 {
5 text = " Hello Silverlight! ";
6 }
7 public string GetText()
8 {
9 return text;
10 }
11 public void SetText( string newText)
12 {
13 this.text = newText;
14
15 if (TextChanged != null)
16 {
17 TextChanged( this, EventArgs.Empty);
18 }
19 }
20
21 string text;
22 public event EventHandler TextChanged;
23 }
3, 通过以上的修改,完成模块对外接口及其实现。接下来, 需要在UI上加一些操作,用来与模块进行交互。在ModuleAViewOne.xaml中绑定好后,在ModuleAViewOneViewModel中更改代码如下:
1
public ModuleAViewOneViewModel(ITextService textService)
2 {
3 this.textService = textService;
4
5 this.textService.TextChanged += (s, e) => {
6 if (PropertyChanged != null)
7 {
8 PropertyChanged( this, new PropertyChangedEventArgs( " Text "));
9 }
10 };
11 }
12 public string Text
13 {
14 get { return textService.GetText(); }
15 }
16 public ICommand OnUpdateText
17 {
18 get
19 {
20 if (onUpdateText == null)
21 {
22 onUpdateText = new DelegateCommand< string>(
23 OnTextChanged);
24 }
25 return onUpdateText;
26 }
27 }
28
29 private ICommand onUpdateText;
30 ITextService textService;
31
32 void OnTextChanged( string newText)
33 {
34 textService.SetText(newText);
35 }
36
37 public event PropertyChangedEventHandler PropertyChanged;
38 }
2 {
3 this.textService = textService;
4
5 this.textService.TextChanged += (s, e) => {
6 if (PropertyChanged != null)
7 {
8 PropertyChanged( this, new PropertyChangedEventArgs( " Text "));
9 }
10 };
11 }
12 public string Text
13 {
14 get { return textService.GetText(); }
15 }
16 public ICommand OnUpdateText
17 {
18 get
19 {
20 if (onUpdateText == null)
21 {
22 onUpdateText = new DelegateCommand< string>(
23 OnTextChanged);
24 }
25 return onUpdateText;
26 }
27 }
28
29 private ICommand onUpdateText;
30 ITextService textService;
31
32 void OnTextChanged( string newText)
33 {
34 textService.SetText(newText);
35 }
36
37 public event PropertyChangedEventHandler PropertyChanged;
38 }