Windows Phone 7 MVVM模式数据绑定和传递参数

数据绑定使用了ObservableCollection<T> 类来实现,ViewModel通过继承GalaSoft.MvvmLight.ViewModelBase类来实现,Command

使用GalaSoft.MvvmLight.Command.RelayCommand<T>来实现。

ObservableCollection<T>表示一个动态数据集合,在添加项、移除项或刷新整个列表时,此集合将提供通知。

客户列表绑定客户的名字、QQ、地址信息,单击的时候显示客户的全部详细信息。

 

 

View层

 

  
  
  
  
  1. <phone:PhoneApplicationPage 
  2.    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  3.    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
  4.    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" 
  5.    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" 
  6.    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  7.    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  8.    xmlns:Custom="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" xmlns:GalaSoft_MvvmLight_Command="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP7" 
  9.    x:Class="MvvmLight5.MainPage" 
  10.    FontFamily="{StaticResource PhoneFontFamilyNormal}" 
  11.    FontSize="{StaticResource PhoneFontSizeNormal}" 
  12.    Foreground="{StaticResource PhoneForegroundBrush}" 
  13.    SupportedOrientations="Portrait" 
  14.    Orientation="Portrait" 
  15.    mc:Ignorable="d" 
  16.    d:DesignWidth="480" 
  17.    d:DesignHeight="768" 
  18.    shell:SystemTray.IsVisible="True" 
  19.    DataContext="{Binding Main, Source={StaticResource Locator}}"> 
  20.     <!--绑定ViewModel中的Main实例对象 资源在App.xaml中进行了加载--> 
  21.  
  22.    <Grid 
  23.       x:Name="LayoutRoot" 
  24.       Background="Transparent"> 
  25.       <Grid.RowDefinitions> 
  26.          <RowDefinition  Height="Auto" /> 
  27.          <RowDefinition Height="*" /> 
  28.       </Grid.RowDefinitions> 
  29.  
  30.       <StackPanel x:Name="TitlePanel"  Grid.Row="0" Margin="24,24,0,12"> 
  31.          <TextBlock 
  32.             x:Name="ApplicationTitle" 
  33.             Text="{Binding ApplicationTitle}" 
  34.             Style="{StaticResource PhoneTextNormalStyle}" /> 
  35.          <TextBlock 
  36.             x:Name="PageTitle" 
  37.             Text="{Binding PageName}" 
  38.             Margin="-3,-8,0,0" 
  39.             Style="{StaticResource PhoneTextTitle1Style}" /> 
  40.       </StackPanel> 
  41.  
  42.       <Grid  x:Name="ContentGrid" Grid.Row="1"> 
  43.          <ListBox  x:Name="PersonListBox"   Margin="10" ItemsSource="{Binding Customers}"> 
  44.                 <!--绑定MainViewModel的Customers数据--> 
  45.             <ListBox.ItemTemplate> 
  46.                <DataTemplate> 
  47.                   <StackPanel> 
  48.                      <StackPanel 
  49.                         x:Name="DataTemplateStackPanel" 
  50.                         Orientation="Horizontal"> 
  51.                         <TextBlock 
  52.                            x:Name="Name" 
  53.                            Text="{Binding Name}" 
  54.                            Margin="0,0,5,0" 
  55.                            Style="{StaticResource PhoneTextExtraLargeStyle}" /> 
  56.                         <TextBlock 
  57.                            x:Name="QQ" 
  58.                            Text="{Binding QQ}" 
  59.                            Margin="0" 
  60.                            Style="{StaticResource PhoneTextExtraLargeStyle}" /> 
  61.                      </StackPanel> 
  62.                      <TextBlock 
  63.                         x:Name="Email" 
  64.                         Text="{Binding Address}" 
  65.                         Margin="0" 
  66.                         Style="{StaticResource PhoneTextSubtleStyle}" /> 
  67.  
  68.                   </StackPanel> 
  69.                </DataTemplate> 
  70.             </ListBox.ItemTemplate> 
  71.                 <!--添加System.Windows.Interactivity触发器处理事件,放在ListBox里面--> 
  72.              <Custom:Interaction.Triggers> 
  73.                  <!--当选中客户的时候触发该事件--> 
  74.                 <Custom:EventTrigger EventName="SelectionChanged"> 
  75.                         <GalaSoft_MvvmLight_Command:EventToCommand x:Name="SelectionCommand" Command="{Binding DetailsPageCommand, Mode=OneWay}" CommandParameter="{Binding SelectedItem, ElementName=PersonListBox}"/> 
  76.                         <!--传递的参数为ListBox选中的Customer对象--> 
  77.                  </Custom:EventTrigger> 
  78.              </Custom:Interaction.Triggers> 
  79.          </ListBox> 
  80.  
  81.       </Grid> 
  82.    </Grid> 
  83. </phone:PhoneApplicationPage> 

ViewModel层

ViewModelLocator是对ViewModel进行初始化和清理的集中处理的类 添加资源的时候只需要添加这一个类就可以了。

ViewModelLocator.cs

 

  
  
  
  
  1. namespace MvvmLight5.ViewModel  
  2. {  
  3.    public class ViewModelLocator  
  4.    {  
  5.       private static MainViewModel _main;  
  6.  
  7.       /// <summary> 
  8.       /// 初始化  在这里创建ViewModel  可以将多个ViewModel在这里一起创建  
  9.       /// </summary> 
  10.       public ViewModelLocator()  
  11.       {  
  12.          CreateMain();  
  13.  
  14.       }  
  15.  
  16.       /// <summary> 
  17.       /// 获取MainViewModel的静态的实例对象  
  18.       /// </summary> 
  19.       public static MainViewModel MainStatic  
  20.       {  
  21.           get  
  22.           {  
  23.               if (_main == null)  
  24.               {  
  25.                   CreateMain();  
  26.               }  
  27.  
  28.               return _main;  
  29.           }  
  30.       }  
  31.  
  32.       /// <summary> 
  33.       /// 获取MainViewModel的实例对象  
  34.       /// </summary> 
  35.       public MainViewModel Main  
  36.       {  
  37.           get  
  38.           {  
  39.               return MainStatic;  
  40.           }  
  41.       }  
  42.  
  43.       /// <summary> 
  44.       ///清理MainViewModel 退出程序的时候进行清理  在App.xmal.cs中调用  
  45.       /// </summary> 
  46.       public static void ClearMain()  
  47.       {  
  48.          _main.Cleanup();  
  49.          _main = null;  
  50.       }  
  51.  
  52.       /// <summary> 
  53.       /// 创建MainViewModel  
  54.       /// </summary> 
  55.       public static void CreateMain()  
  56.       {  
  57.          if ( _main == null )  
  58.          {  
  59.             _main = new MainViewModel();  
  60.          }  
  61.       }  
  62.    }  

MainViewModel.cs

 

  
  
  
  
  1. using System.Collections.ObjectModel;  
  2. using GalaSoft.MvvmLight;  
  3. using GalaSoft.MvvmLight.Command;  
  4. using MvvmLight5.Model;  
  5.  
  6. namespace MvvmLight5.ViewModel  
  7. {  
  8.    public class MainViewModel : ViewModelBase  
  9.    {  
  10.  
  11.       /// <summary> 
  12.       /// 数据绑定的客户列表  
  13.       /// </summary> 
  14.       public ObservableCollection<Customer> Customers  
  15.       {  
  16.          get  
  17.          {  
  18.             var customerCollection = new CustomerCollection();  
  19.             return customerCollection.Customers;  
  20.          }  
  21.       }  
  22.       //定义Command  
  23.       public RelayCommand<Customer> DetailsPageCommand  
  24.       {  
  25.          get;  
  26.          private set;  
  27.       }  
  28.  
  29.       public string ApplicationTitle  
  30.       {  
  31.          get  
  32.          {  
  33.             return "MVVM LIGHT";  
  34.          }  
  35.       }  
  36.  
  37.       public string PageName  
  38.       {  
  39.          get  
  40.          {  
  41.             return "客户列表如下:";  
  42.          }  
  43.       }  
  44.  
  45.       public string Welcome  
  46.       {  
  47.          get  
  48.          {  
  49.             return "Welcome to MVVM Light";  
  50.          }  
  51.       }  
  52.  
  53.       /// <summary> 
  54.       /// 初始化 MainViewModel  
  55.       /// </summary> 
  56.       public MainViewModel()  
  57.       {  
  58.           //初始化Command  
  59.          DetailsPageCommand = new RelayCommand<Customer>( ( msg ) => GoToDetailsPage( msg ) );  
  60.       }  
  61.  
  62.       private object GoToDetailsPage( Customer msg )  
  63.       {  
  64.           System.Windows.MessageBox.Show("客户的详细资料如下    名字:" + msg.Name + "  城市:" + msg.City + "  地址:" + msg.Address + "  电话:" + msg.Phone + "  QQ:" + msg.QQ);  
  65.          return null;  
  66.       }  
  67.    }  

Model层

Customers.cs

 

  
  
  
  
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Collections.ObjectModel;  
  4.  
  5. namespace MvvmLight5.Model  
  6. {  
  7.    public class CustomerCollection  
  8.    {  
  9.       //在这里绑定数据使用了ObservableCollection<T> 类    
  10.       private readonly ObservableCollection<Customer> _customers = new ObservableCollection<Customer>();  
  11.       public ObservableCollection<Customer> Customers  
  12.       {  
  13.          get { return _customers; }  
  14.       }  
  15.  
  16.       public Customer GetCustomerByID( int id )  
  17.       {  
  18.          return _customers[ id ];  
  19.       }  
  20.  
  21.       public CustomerCollection()  
  22.       {  
  23.          try  
  24.          {  
  25.             GenerateCustomers();  
  26.          }  
  27.          catch ( Exception e )  
  28.          {  
  29.             System.Windows.MessageBox.Show( "Exception: " + e.Message );  
  30.          }  
  31.       }  
  32.        //初始化数据  
  33.       public void GenerateCustomers()  
  34.       {  
  35.             _customers.Add( new Customer(1,"黄小琥","台湾高雄市十六街8号","高雄","13457789907","3232","[email protected]") );  
  36.             _customers.Add(new Customer(2, "李开复", "北京市东城区十六街8号", "北京", "136589907", "787222894", "[email protected]"));  
  37.             _customers.Add(new Customer(3, "周杰伦", "台湾台北市十六街8号", "台北", "145455779907", "2323266", "[email protected]"));  
  38.             _customers.Add(new Customer(4, "郎咸平", "香港十六街8号", "香港", "145489907", "787222894", "[email protected]"));  
  39.             _customers.Add(new Customer(5, "加菲猫", "高雄市十六街8号", "高雄市", "15777789907", "333434", "[email protected]"));  
  40.             _customers.Add(new Customer(6, "灰太狼", "台湾第三代市十六街8号", "高雄市", "134357789907", "23232", "[email protected]"));  
  41.             _customers.Add(new Customer(7, "喜洋洋", "台湾高雄市十六街8号", "高雄市", "134544589907", "23232777", "[email protected]"));  
  42.             _customers.Add(new Customer(8, "春哥", "台湾所得税十六街8号", "高雄市", "13453445907", "888888", "[email protected]"));  
  43.            
  44.       }  
  45.    }  
  46.  
  47.    public class Customer  
  48.    {  
  49.       public int ID { get; set; }  
  50.  
  51.       public string Name { get ; set; }  
  52.  
  53.       public string Address { get; set; }  
  54.  
  55.       public string City { get; set; }  
  56.  
  57.       public string Phone { get; set; }  
  58.  
  59.       public string QQ { get; set; }  
  60.  
  61.       public string Email { get; set; }  
  62.  
  63.       public Customer()  
  64.       { }  
  65.  
  66.       public Customer(  
  67.          int id,  
  68.           string name,  
  69.           string address,  
  70.           string city,  
  71.           string phone,  
  72.           string qq,  
  73.           string email )  
  74.       {  
  75.          ID = id;  
  76.          Name = name;  
  77.          Address = address;  
  78.          City = city;  
  79.          PhonePhone = Phone;  
  80.          QQ = qq;  
  81.          Email = email;  
  82.       }  
  83.    }  

App.xaml 程序初始化处理

 

  
  
  
  
  1. <Application x:Class="MvvmLight5.App" 
  2.              xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
  4.              xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" 
  5.              xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" 
  6.              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  7.              xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  8.              mc:Ignorable="d" 
  9.              xmlns:vm="clr-namespace:MvvmLight5.ViewModel"> 
  10.  
  11.     <!--Application Resources--> 
  12.     <Application.Resources> 
  13.         <vm:ViewModelLocator x:Key="Locator" 
  14.                              d:IsDataSource="True" /> 
  15.     </Application.Resources> 
  16.  
  17.     <Application.ApplicationLifetimeObjects> 
  18.         <!--Required object that handles lifetime events for the application--> 
  19.         <shell:PhoneApplicationService Launching="Application_Launching" 
  20.                                        Closing="Application_Closing" 
  21.                                        Activated="Application_Activated" 
  22.                                        Deactivated="Application_Deactivated" /> 
  23.     </Application.ApplicationLifetimeObjects> 
  24.  
  25. </Application> 

cs

 // 清理ViewModel资源
      private void Application_Closing( object sender, ClosingEventArgs e )
      {
         ViewModelLocator.ClearMain();
      }
 

你可能感兴趣的:(windows,传递参数,phone,数据绑定,7,MVVM模式)