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

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

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

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

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

View层

<phone:PhoneApplicationPage
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone
="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell
="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d
="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc
="http://schemas.openxmlformats.org/markup-compatibility/2006"
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"
x:Class
="MvvmLight5.MainPage"
FontFamily
="{StaticResource PhoneFontFamilyNormal}"
FontSize
="{StaticResource PhoneFontSizeNormal}"
Foreground
="{StaticResource PhoneForegroundBrush}"
SupportedOrientations
="Portrait"
Orientation
="Portrait"
mc:Ignorable
="d"
d:DesignWidth
="480"
d:DesignHeight
="768"
shell:SystemTray.IsVisible
="True"
DataContext
="{Binding Main, Source={StaticResource Locator}}">
<!--绑定ViewModel中的Main实例对象 资源在App.xaml中进行了加载-->

<Grid
x:Name="LayoutRoot"
Background
="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>

<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="24,24,0,12">
<TextBlock
x:Name="ApplicationTitle"
Text
="{Binding ApplicationTitle}"
Style
="{StaticResource PhoneTextNormalStyle}" />
<TextBlock
x:Name="PageTitle"
Text
="{Binding PageName}"
Margin
="-3,-8,0,0"
Style
="{StaticResource PhoneTextTitle1Style}" />
</StackPanel>

<Grid x:Name="ContentGrid" Grid.Row="1">
<ListBox x:Name="PersonListBox" Margin="10" ItemsSource="{Binding Customers}">
<!--绑定MainViewModel的Customers数据-->
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<StackPanel
x:Name="DataTemplateStackPanel"
Orientation
="Horizontal">
<TextBlock
x:Name="Name"
Text
="{Binding Name}"
Margin
="0,0,5,0"
Style
="{StaticResource PhoneTextExtraLargeStyle}" />
<TextBlock
x:Name="QQ"
Text
="{Binding QQ}"
Margin
="0"
Style
="{StaticResource PhoneTextExtraLargeStyle}" />
</StackPanel>
<TextBlock
x:Name="Email"
Text
="{Binding Address}"
Margin
="0"
Style
="{StaticResource PhoneTextSubtleStyle}" />

</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
<!--添加System.Windows.Interactivity触发器处理事件,放在ListBox里面-->
<Custom:Interaction.Triggers>
<!--当选中客户的时候触发该事件-->
<Custom:EventTrigger EventName="SelectionChanged">
<GalaSoft_MvvmLight_Command:EventToCommand x:Name="SelectionCommand" Command="{Binding DetailsPageCommand, Mode=OneWay}" CommandParameter="{Binding SelectedItem, ElementName=PersonListBox}"/>
<!--传递的参数为ListBox选中的Customer对象-->
</Custom:EventTrigger>
</Custom:Interaction.Triggers>
</ListBox>

</Grid>
</Grid>
</phone:PhoneApplicationPage>

ViewModel层

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

ViewModelLocator.cs

namespace MvvmLight5.ViewModel
{
public class ViewModelLocator
{
private static MainViewModel _main;

/// <summary>
/// 初始化 在这里创建ViewModel 可以将多个ViewModel在这里一起创建
/// </summary>
public ViewModelLocator()
{
CreateMain();

}

/// <summary>
/// 获取MainViewModel的静态的实例对象
/// </summary>
public static MainViewModel MainStatic
{
get
{
if (_main == null)
{
CreateMain();
}

return _main;
}
}

/// <summary>
/// 获取MainViewModel的实例对象
/// </summary>
public MainViewModel Main
{
get
{
return MainStatic;
}
}

/// <summary>
///清理MainViewModel 退出程序的时候进行清理 在App.xmal.cs中调用
/// </summary>
public static void ClearMain()
{
_main.Cleanup();
_main
= null;
}

/// <summary>
/// 创建MainViewModel
/// </summary>
public static void CreateMain()
{
if ( _main == null )
{
_main
= new MainViewModel();
}
}
}
}

MainViewModel.cs

using System.Collections.ObjectModel;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using MvvmLight5.Model;

namespace MvvmLight5.ViewModel
{
public class MainViewModel : ViewModelBase
{


/// <summary>
/// 数据绑定的客户列表
/// </summary>
public ObservableCollection<Customer> Customers
{
get
{
var customerCollection
= new CustomerCollection();
return customerCollection.Customers;
}
}
//定义Command
public RelayCommand<Customer> DetailsPageCommand
{
get;
private set;
}

public string ApplicationTitle
{
get
{
return "MVVM LIGHT";
}
}

public string PageName
{
get
{
return "客户列表如下:";
}
}

public string Welcome
{
get
{
return "Welcome to MVVM Light";
}
}

/// <summary>
/// 初始化 MainViewModel
/// </summary>
public MainViewModel()
{
//初始化Command
DetailsPageCommand = new RelayCommand<Customer>( ( msg ) => GoToDetailsPage( msg ) );
}

private object GoToDetailsPage( Customer msg )
{
System.Windows.MessageBox.Show(
"客户的详细资料如下 名字:" + msg.Name + " 城市:" + msg.City + " 地址:" + msg.Address + " 电话:" + msg.Phone + " QQ:" + msg.QQ);
return null;
}
}
}

Model层

Customers.cs

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace MvvmLight5.Model
{
public class CustomerCollection
{
//在这里绑定数据使用了ObservableCollection<T> 类
private readonly ObservableCollection<Customer> _customers = new ObservableCollection<Customer>();
public ObservableCollection<Customer> Customers
{
get { return _customers; }
}

public Customer GetCustomerByID( int id )
{
return _customers[ id ];
}

public CustomerCollection()
{
try
{
GenerateCustomers();
}
catch ( Exception e )
{
System.Windows.MessageBox.Show(
"Exception: " + e.Message );
}
}
//初始化数据
public void GenerateCustomers()
{
_customers.Add(
new Customer(1,"黄小琥","台湾高雄市十六街8号","高雄","13457789907","3232","huangxiaohu@qq.com") );
_customers.Add(
new Customer(2, "李开复", "北京市东城区十六街8号", "北京", "136589907", "787222894", "huasdsdu@qq.com"));
_customers.Add(
new Customer(3, "周杰伦", "台湾台北市十六街8号", "台北", "145455779907", "2323266", "232@qq.com"));
_customers.Add(
new Customer(4, "郎咸平", "香港十六街8号", "香港", "145489907", "787222894", "6ggg@qq.com"));
_customers.Add(
new Customer(5, "加菲猫", "高雄市十六街8号", "高雄市", "15777789907", "333434", "2323@qq.com"));
_customers.Add(
new Customer(6, "灰太狼", "台湾第三代市十六街8号", "高雄市", "134357789907", "23232", "3232@qq.com"));
_customers.Add(
new Customer(7, "喜洋洋", "台湾高雄市十六街8号", "高雄市", "134544589907", "23232777", "88sds@qq.com"));
_customers.Add(
new Customer(8, "春哥", "台湾所得税十六街8号", "高雄市", "13453445907", "888888", "sdsgg@qq.com"));

}
}

public class Customer
{
public int ID { get; set; }

public string Name { get ; set; }

public string Address { get; set; }

public string City { get; set; }

public string Phone { get; set; }

public string QQ { get; set; }

public string Email { get; set; }

public Customer()
{ }

public Customer(
int id,
string name,
string address,
string city,
string phone,
string qq,
string email )
{
ID
= id;
Name
= name;
Address
= address;
City
= city;
Phone
= Phone;
QQ
= qq;
Email
= email;
}
}
}

App.xaml 程序初始化处理

<Application x:Class="MvvmLight5.App"
xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone
="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell
="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:mc
="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d
="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable
="d"
xmlns:vm
="clr-namespace:MvvmLight5.ViewModel">

<!--Application Resources-->
<Application.Resources>
<vm:ViewModelLocator x:Key="Locator"
d:IsDataSource
="True" />
</Application.Resources>

<Application.ApplicationLifetimeObjects>
<!--Required object that handles lifetime events for the application-->
<shell:PhoneApplicationService Launching="Application_Launching"
Closing
="Application_Closing"
Activated
="Application_Activated"
Deactivated
="Application_Deactivated" />
</Application.ApplicationLifetimeObjects>

</Application>

cs

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

posted on 2011-03-27 18:42  linzheng  阅读(3817)  评论(22编辑  收藏  举报

导航