Silverlight学习(二)

好久没来写博客了,这期间经历了春节,也因为忙于一个项目,所以博客被疏忽了。最近一段时间一直在用silverlight做项目,从来一开始的不熟悉渐渐的开始上手。今天记录一下自己学习prism的一些samplecode。

silvierlight目前的主流架构是Silverlight+MVVM+WCF RIA,说来惭愧本人做项目的时候对设计模式不是很了解。MVVM设计模式是指模型(Model)-视图(View)-视图模型(ViewModel),MVVM设计模式能够将程序的UI设计和逻辑设计分开,这样能够节省开发人员的大量时间,也可以使代码更容易维护和升级等。View是指UI,是用来展示的,Model可以定义一些数据访问的实体类,ViewModel是连接model层和view层的桥梁,它是中间层,主要用来一些业务逻辑的设计,这里包括与数据库的交互。

Prism是微软提供的一个用于Silverlight和WPF开发的框架。

下面重点讲讲Prim+MVVM的实现。

1.需要新建一个Silverlight应用程序,分为Silverlight服务端和客户端两部分,需要在Silverlight客户端添加View、Model、ViewModel几个文件夹,分别对应MVVM设计模式。

 

2.在Model中添加类Questionnaire

 1     /// <summary>

 2     /// 定义Model,如果需要监听属性的变化,需要继承INotifyPropertyChanged类

 3     /// </summary>

 4     public class Questionnaire:INotifyPropertyChanged

 5     {

 6         private string favoriteColor;

 7         public Questionnaire()

 8         {

 9         }

10         public event PropertyChangedEventHandler PropertyChanged;

11 

12         public string Name { get; set; }

13 

14         public int Age { get; set; }

15 

16         public string Quest { get; set; }

17 

18         public string FavoriteColor

19         {

20             get

21             {

22                 return this.favoriteColor;

23             }

24 

25             set

26             {

27                 //监听颜色属性的变化

28                 if (value != this.favoriteColor)

29                 {

30                     this.favoriteColor = value;

31                     if (this.PropertyChanged != null)

32                     {

33                         this.PropertyChanged(this, new PropertyChangedEventArgs("FavoriteColor"));

34                     }

35                 }

36             }

37         }

38         private string getText;

39         public string GetText

40         {

41             get { return getText; }

42             set

43             {

44                 //监听字符的变化

45                 if (value != this.getText)

46                 {

47                     this.getText = value;

48                     if (this.PropertyChanged != null)

49                     {

50                         this.PropertyChanged(this, new PropertyChangedEventArgs("GetText"));

51                     }

52                 }

53             }

54         }

55     }
Model

3.添加在modelview文件夹中添加questionnaireviewmodel类

 1   /// <summary>

 2     /// 定义viewModel

 3     /// </summary>

 4     public class QuestionnaireViewModel

 5     {

 6         private readonly  Questionnaire questionnaire;

 7 

 8         public QuestionnaireViewModel()

 9         {

10             this.questionnaire = new Questionnaire();

11             this.AllColors = new[] { "Red", "Blue", "Green" };

12 

13             this.SubmitCommand = new DelegateCommand<object>(this.OnSubmit);//实例化一个command,DelegateCommand引用类库 Microsoft.Practices.Prism.Commands

14      

15         }

16         /// <summary>

17         /// 定义Model的属性

18         /// </summary>

19         public Questionnaire Questionnaire

20         {

21             get { return this.questionnaire; }

22         }

23 

24         public IEnumerable<string> AllColors { get; private set; }

25         /// <summary>

26         /// 定义一个command,可以绑定到控件上

27         /// </summary>

28         public ICommand SubmitCommand { get; private set; }

29 

30         private void OnSubmit(object obj)

31         {

32             questionnaire.GetText = this.BuildResultString().ToString(); 

33         

34         }

35  

36 

37         private string BuildResultString()

38         {

39             StringBuilder builder = new StringBuilder();

40             builder.Append("Name: ");

41             builder.Append(this.questionnaire.Name);

42             builder.Append("\nAge: ");

43             builder.Append(this.questionnaire.Age);

44             builder.Append("\nQuestion 1: ");

45             builder.Append(this.questionnaire.Quest);

46             builder.Append("\nQuestion 2: ");

47             builder.Append(this.questionnaire.FavoriteColor);

48             return builder.ToString();

49         }

50     }
View Code

4.在view文件夹中添加QuestionView,用来显示

 d:DesignHeight="300" d:DesignWidth="400">

    <!--绑定ViewModel,获取上下文消息,这里面一般包括需要绑定的字段、类、方法等-->

    <UserControl.DataContext>

        <vm:QuestionnaireViewModel></vm:QuestionnaireViewModel>

    </UserControl.DataContext>

    <Grid x:Name="LayoutRoot" Background="White">

        <Grid.RowDefinitions>

            <RowDefinition Height="Auto"/>

            <RowDefinition Height="30"/>

        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="*"/>

            <ColumnDefinition Width="Auto"/>



        </Grid.ColumnDefinitions>



        <ScrollViewer Grid.Row="0" Grid.ColumnSpan="3" VerticalAlignment="Stretch">

            <Grid>

                <Grid.RowDefinitions>

                    <RowDefinition Height="Auto"/>

                    <RowDefinition Height="Auto"/>

                    <RowDefinition Height="Auto"/>

                    <RowDefinition Height="Auto"/>

                </Grid.RowDefinitions>



                <Border Grid.Row="0" >

                    <Grid>

                        <Grid.RowDefinitions>

                            <RowDefinition Height="Auto" />

                            <RowDefinition Height="Auto" />

                        </Grid.RowDefinitions>

                        <Grid.ColumnDefinitions>

                            <ColumnDefinition Width="Auto" />

                            <ColumnDefinition Width="Auto" />

                        </Grid.ColumnDefinitions>



                        <TextBlock Grid.Column="0" Grid.Row="0" VerticalAlignment="Bottom"><Run Text="Name"/></TextBlock>

                        <TextBox x:Name="NameTextBox" Grid.Column="1" Grid.Row="0" Text="{Binding Questionnaire.Name, Mode=TwoWay}" Width="150" Margin="2" />



                        <TextBlock Grid.Column="0" Grid.Row="1" VerticalAlignment="Bottom"><Run Text="Age"/></TextBlock>

                        <TextBox x:Name="AgeTextBox" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Left" Text="{Binding Questionnaire.Age, Mode=TwoWay}" MaxLength="3" Width="40" Margin="2" />



                    </Grid>

                </Border>



                <Grid Grid.Row="1" Margin="5" >

                    <Grid.RowDefinitions>

                        <RowDefinition Height="Auto"/>

                        <RowDefinition Height="Auto"/>

                    </Grid.RowDefinitions>

                    <Grid.ColumnDefinitions>

                        <ColumnDefinition Width="*"/>

                    </Grid.ColumnDefinitions>



                    <TextBlock Grid.Row="0" Text="What is your quest?" Style="{StaticResource QuestionLabelStyle}" />

                    <TextBox x:Name="Question1Response" Grid.Row="1" Text="{Binding TestClass.Quest, Mode=TwoWay}" />

                </Grid>



                <Grid Grid.Row="2" Margin="5">

                    <Grid.ColumnDefinitions>

                        <ColumnDefinition Width="*"/>

                    </Grid.ColumnDefinitions>

                    <Grid.RowDefinitions>

                        <RowDefinition Height="Auto"/>

                        <RowDefinition Height="Auto"/>

                    </Grid.RowDefinitions>



                    <TextBlock Grid.Row="0" Style="{StaticResource QuestionLabelStyle}">

                        <Run Text="What is your favorite "/><Run x:Name="ColorRun" Text="color" Foreground="{Binding Questionnaire.FavoriteColor, TargetNullValue=Black}"/><Run Text="?"/>

                    </TextBlock>



                    <Border Grid.Row="1" Style="{StaticResource BorderBrush}">

                        <ListBox x:Name="Colors" IsTabStop="False" ItemsSource="{Binding AllColors}" Margin="5"

                                 SelectedItem="{Binding Questionnaire.FavoriteColor, Mode=TwoWay}">

                        </ListBox>

                    </Border>

                </Grid>

            </Grid>

        </ScrollViewer>

        <TextBlock Grid.Row="1" Grid.Column="0" Text="{Binding Path=Questionnaire.GetText,Mode=TwoWay}" HorizontalAlignment="Left" VerticalAlignment="Top" Width="300" Height="30"></TextBlock>

        <Button x:Name="SubmitButton" Command="{Binding SubmitCommand}" Grid.Row="1" Grid.Column="1" Content="Submit" Height="23" HorizontalAlignment="Right" Width="75"/>

    </Grid>
View

设计前台,并未控件绑定数据。其中Button控件绑定了无参数的ICommand命令,后台为DelegateCommand。通过Button控件 我们可以获取到数据源的变化,并将它显示到页面上。。

5.在MainPage主页面添加已经设计好的页面。

 1 <UserControl xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation" 

 2     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

 3     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

 4     x:Class="SilverlightApplication4.MainPage"

 5              xmlns:view="clr-namespace:SilverlightApplication4.View"

 6              xmlns:viewModel="clr-namespace:SilverlightApplication4.ViewModel"

 7     Width="640" Height="480">

 8     <Grid x:Name="LayoutRoot" Background="White" >

 9         <view:QuestionnaireView></view:QuestionnaireView>

10             <!--<view:PersonViewList DataContext="myele"></view:PersonViewList>-->

11     </Grid>

12 </UserControl>
Main

 

这样就玩一个了基本的Silverlight应用程序,本程序未设计到与数据库的交互,下一篇将会有所涉及。

你可能感兴趣的:(silverlight)