Windows Phone中 MVVM框架

MVVM(Model View ViewModel)是由MVC和MVP模式发展来的一种模式,它主要目的就是将应用程序的代码和界面分离开,这样界面开发可以更专注于设计界面,也使得UI界面更容易变换和测试,下面来看一下这3层的主要功能

1.Model层

数据访问层,一般定义为一个或多个类,以面向对象的方式将数据表示出来。

2.View层

表示层,UI界面的实现以及通过Binding和Command来实现与ViewModel层的交互

3.ViewModel层

负责View和Model之间的信息转换,将View的Command传到Model,以及通过Binding来实现与和View层的数据传递。

下面是一个MVVM模式的数据绑定实例:

思路:

1.定义一个实体类(Model层)来保存数据。

2.创建ViewModel层:声明一个集合类(ObservableCollection<T>)来作为绑定的数据源,且ViewModel层必须是实现了INotifyPropertyChanged接口,这样在数据源发生变化时才能及时通知Binding来更改目标值(View层中)的变化。

3.创建View层。如果要绑定ViewModel层中的数据,必须将ViewModel层中的命名空间引用,然后添加到Resource中,并设置一个key(本实例中设置为“food”),然后将Resource中的资源赋值给Grid控件中的DataContent属性,则在Grid中就可以使用ViewModel层中的数据源了。

Food.cs代码如下(Model层)

namespace BindingDataDemo.Model
{
    public class Food
    {
        public string Name
        {
            get;
            set;
        }

        public string Description
        {
            get;
            set;
        }

        public string IconUri
        {
            get;
            set;
        }

        public string Type
        {
            get;
            set;
        }

    }
}
Food.cs

 

FoodViewModel.cs代码如下(ViewModel层)

using System;
using System.ComponentModel;
using BindingDataDemo.Model;
using System.Collections.ObjectModel;

namespace BindingDataDemo.ViewModel
{
    public class FoodViewModel : INotifyPropertyChanged
    {
        private  ObservableCollection<Food> _allFood;

        public ObservableCollection<Food> AllFood
        {
            get
            {
                if (_allFood == null)
                    _allFood = new ObservableCollection<Food>();

                return _allFood;
            }
            set
            {
                if (_allFood != value)
                {
                    _allFood = value;
                    NotifyPropertyChanged("AllFood");
                }
            }
        }

        public FoodViewModel()
        {
             try   
            {
                Food item0 = new Food() { Name = "西红柿", IconUri = "Images/Tomato.png", Type = "Healthy" ,Description="西红柿的味道不错。" };
                Food item1 = new Food() { Name = "茄子", IconUri = "Images/Beer.png", Type = "NotDetermined", Description = "不知道这个是否好吃。" };
                Food item2 = new Food() { Name = "火腿", IconUri = "Images/fries.png", Type = "Unhealthy", Description = "这是不健康的食品。" };
                Food item3 = new Food() { Name = "三明治", IconUri = "Images/Hamburger.png", Type = "Unhealthy" ,Description="肯德基的好吃?" };
                Food item4 = new Food() { Name = "冰激凌", IconUri = "Images/icecream.png", Type = "Healthy", Description = "给小朋友吃的。" };
                Food item5 = new Food() { Name = "Pizza", IconUri = "Images/Pizza.png", Type = "Unhealthy" ,Description="这个非常不错。" };
                Food item6 = new Food() { Name = "辣椒", IconUri = "Images/Pepper.png", Type = "Healthy", Description = "我不喜欢吃这东西。" };
                AllFood.Add(item0);
                AllFood.Add(item1);
                AllFood.Add(item2);
                AllFood.Add(item3);
                AllFood.Add(item4);
                AllFood.Add(item5);
                AllFood.Add(item6);
            }      
            catch ( Exception e )  
            {         
                System.Windows.MessageBox.Show( "Exception: " + e.Message );       
            }   
        }
        
        // 定义PropertyChanged 事件
        public event PropertyChangedEventHandler PropertyChanged;

        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }  


    }
}
FoodViewModel.cs

 

MainPage.xaml代码如下(View层)

<phone:PhoneApplicationPage 
    x:Class="BindingDataDemo.MainPage"
    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:my="clr-namespace:BindingDataDemo.ViewModel" 
    mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    shell:SystemTray.IsVisible="True">
    <phone:PhoneApplicationPage.Resources>
        <my:FoodViewModel x:Key="food" />
    </phone:PhoneApplicationPage.Resources>

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

        <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28">
            <TextBlock x:Name="ApplicationTitle" Text="MY APPLICATION" Style="{StaticResource PhoneTextNormalStyle}"/>
            <TextBlock x:Name="PageTitle" Text="数据绑定" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
        </StackPanel>
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0" DataContext="{StaticResource food }">
            <ListBox x:Name="listBox" HorizontalContentAlignment="Stretch" ItemsSource="{Binding AllFood}">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                       <StackPanel Orientation="Horizontal" Background="Gray" Width="450" Margin="10">
                            <Image Source="{Binding IconUri}" Stretch="None"/>
                            <TextBlock Text="{Binding Name}" FontSize="40" Width="150"/>
                            <TextBlock Text="{Binding Description}" FontSize="20" Width="280"/>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </Grid>
    </Grid>

</phone:PhoneApplicationPage>
MainPage.xaml

 

posted @ 2015-04-12 19:23  runninglzw  阅读(343)  评论(0编辑  收藏  举报