赞
踩
注:本系列学习帖子我在DevDiv.com移动开发社区原创首发
转载请注明出处:BeyondVincent(破船)@DevDiv.com
如果你有什么问题也可以前往交流
下面是首发地址:
在程序中使用视图模型(ViewModel),可以带来很多好处,在开发中值得采纳,视图模型的使用对Metro App开发非常有帮助,通过学习MVC和MVVC你可以了解到试图模型。在这里我将介绍如何定义和使用试图模型,其中包括数据的绑定等内容。
本次程序我以DevDiv论坛的板块为参考数据,写一个视图模型,有一个主画面,画面的左边有一个列表,列表中的数据来自试图模型中板块项列表,同时右边会显示选中板块的介绍。下面是程序的运行图,我们可以先来看看最终效果:
本次学习内容主要包括一下几部分:
1、视图模型(ViewModel)的创建
2、添加页面
3、编写页面相关代码
4、添加资源字典
5、编写XAML
6、程序运行效果图与Demo程序
更多内容请查看下面的帖子
1、视图模型(ViewModel)的创建
对于创建具有可持续性和和可维护性的应用程序,试图模型是必须具有的一个基础部分,它可以让我将应用程序数据与呈现数据给用户的方法相分离。如果不使用视图模型的话,你会发现你的程序越来越难以维护和开发。
在本小节,我首先使用Blank App模版创建了一个名为DevDiv_DataBinding的工程。并在其中创建一个Data目录,然后再Data目录下创建两个新的类文件。分别是ForumItem.cs和ViewModel.cs文件。
ForumItem类的代码如下
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.ComponentModel;
-
- namespace DevDiv_DataBinding.Data
- {
- class ForumItem : INotifyPropertyChanged
- {
- private string name, link, info;// 论坛板块的名称,链接和描述信息
- private int topicCount; // 主题数
- public string Name
- {
- get { return name; }
- set { name = value; NotifyPropertyChanged("Name"); }
- }
- public string Link
- {
- get { return link; }
- set { link = value; NotifyPropertyChanged("Link"); }
- }
- public string Info
- {
- get { return info; }
- set { info = value; NotifyPropertyChanged("info"); }
- }
- public int TopicCount
- {
- get { return topicCount; }
- set { topicCount = value; NotifyPropertyChanged("TopicCount"); }
- }
- public event PropertyChangedEventHandler PropertyChanged;
- private void NotifyPropertyChanged(string propName)
- {
- if (PropertyChanged != null)
- {
- PropertyChanged(this, new PropertyChangedEventArgs(propName));
- }
- }
- }
- }

- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.ComponentModel;
- using System.Collections.ObjectModel;
-
- namespace DevDiv_DataBinding.Data
- {
- class ViewModel : INotifyPropertyChanged
- {
- private ObservableCollection<ForumItem> forumItemList;
- private int selectedItemIndex;
- private string itemDetail;
- public ViewModel()
- {
- forumItemList = new ObservableCollection<ForumItem>();
- selectedItemIndex = -1;
- }
-
- public int SelectedItemIndex
- {
- get { return selectedItemIndex; }
- set
- {
- selectedItemIndex = value; NotifyPropertyChanged("SelectedItemIndex");
- }
- }
-
- public string ItemDetail
- {
- get { return itemDetail; }
- set
- {
- itemDetail = value; NotifyPropertyChanged("ItemDetail");
- }
- }
-
- public ObservableCollection<ForumItem> ForumItemList
- {
- get
- {
- return forumItemList;
- }
- }
-
- public event PropertyChangedEventHandler PropertyChanged;
- private void NotifyPropertyChanged(string propName)
- {
- if (PropertyChanged != null)
- {
- PropertyChanged(this, new PropertyChangedEventArgs(propName));
- }
- }
- }
-
- }

- var rootFrame = new Frame();
- if (!rootFrame.Navigate(typeof(Pages.ListPage)))
- {
- throw new Exception("Failed to create initial page");
- }
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using Windows.Foundation;
- using Windows.Foundation.Collections;
- using Windows.UI.Xaml;
- using Windows.UI.Xaml.Controls;
- using Windows.UI.Xaml.Controls.Primitives;
- using Windows.UI.Xaml.Data;
- using Windows.UI.Xaml.Input;
- using Windows.UI.Xaml.Media;
- using Windows.UI.Xaml.Navigation;
- using DevDiv_DataBinding.Data;
-
- // The Blank Page item template is documented at <a href="\"http://go.microsoft.com/fwlink/?LinkId=234238\"" target="\"_blank\"">http://go.microsoft.com/fwlink/?LinkId=234238</a>
-
- namespace DevDiv_DataBinding.Pages
- {
- /// <summary>
- /// An empty page that can be used on its own or navigated to within a Frame.
- /// </summary>
- public sealed partial class ListPage : Page
- {
- ViewModel viewModel;
-
- public ListPage()
- {
-
- viewModel = new ViewModel();
- viewModel.SelectedItemIndex = -1;
- viewModel.ForumItemList.Add(new ForumItem { Name = "Android开发论坛", TopicCount = 4, Link = "http://www.devdiv.com/forum-110-1.html",
- Info = "Android开发论坛、Android开发者论坛、环境搭建、应用开发、驱动开发、系统移植、文档"});
- viewModel.ForumItemList.Add(new ForumItem { Name = "Android开发资料", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html" });
- viewModel.ForumItemList.Add(new ForumItem { Name = "iOS开发论坛/iPhone开发论坛", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html" });
- viewModel.ForumItemList.Add(new ForumItem { Name = "iOS开发资料/iPhone开发资料", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html" });
- viewModel.ForumItemList.Add(new ForumItem { Name = "微软/诺基亚 Windows Phone开发论坛 ", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html" });
- viewModel.ForumItemList.Add(new ForumItem { Name = "Windows Phone开发资料", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html" });
- viewModel.ForumItemList.Add(new ForumItem { Name = "Windows 8 开发论坛 ", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html",
- Info = "Windows 8 代码、教程、入门、文档、视频"});
- viewModel.ForumItemList.Add(new ForumItem { Name = "Symbian开发论坛", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html" });
- viewModel.ForumItemList.Add(new ForumItem { Name = "Symbian开发论坛", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html" });
- viewModel.ForumItemList.Add(new ForumItem { Name = "Symbian开发论坛", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html" });
- viewModel.ForumItemList.Add(new ForumItem { Name = "Symbian开发论坛", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html" });
- viewModel.ForumItemList.Add(new ForumItem { Name = "Symbian开发论坛", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html" });
- viewModel.ForumItemList.Add(new ForumItem { Name = "Symbian开发论坛", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html" });
-
- this.InitializeComponent();
-
- this.DataContext = viewModel;
- }
-
- /// <summary>
- /// Invoked when this page is about to be displayed in a Frame.
- /// </summary>
- /// <param name="e">Event data that describes how this page was reached. The Parameter
- /// property is typically used to configure the page.</param>
- protected override void OnNavigatedTo(NavigationEventArgs e)
- {
- }
-
- private void ListSelectionChanged(object sender, SelectionChangedEventArgs e)
- {
- viewModel.ItemDetail = ((ForumItem)e.AddedItems[0]).Info;
- if (viewModel.ItemDetail == null || viewModel.ItemDetail.Length == 0)
- {
- viewModel.ItemDetail = ((ForumItem)e.AddedItems[0]).Name;
- }
- }
- }
- }

- <ResourceDictionary
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:local="using:DevDiv_DataBinding.Resources">
- <ResourceDictionary.MergedDictionaries>
- <ResourceDictionary Source="/Common/StandardStyles.xaml" />
- </ResourceDictionary.MergedDictionaries>
-
- <SolidColorBrush x:Key="AppBackgroundColor" Color="#3E790A"/>
- <Style x:Key="ForumListItem" TargetType="TextBlock"
- BasedOn="{StaticResource BasicTextStyle}" >
- <Setter Property="FontSize" Value="38"/>
- <Setter Property="FontWeight" Value="Light"/>
- <Setter Property="Margin" Value="10, 0"/>
- <Setter Property="VerticalAlignment" Value="Center"/>
- </Style>
-
- <DataTemplate x:Key="ForumListItemTemplate">
- <StackPanel Orientation="Horizontal">
- <TextBlock Text="{Binding Name}"
- Style="{StaticResource ForumListItem}"/>
- </StackPanel>
- </DataTemplate>
-
- </ResourceDictionary>

<ResourceDictionary Source="Resources/ForumResourceDictionary.xaml"/>
- <Page
- x:Class="DevDiv_DataBinding.Pages.ListPage"
- IsTabStop="false"
- xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
- xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
- xmlns:local="using:DevDiv_DataBinding.Pages"
- xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
- xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
- mc:Ignorable="d">
-
- <Grid Background="{StaticResource AppBackgroundColor}">
- <Grid.RowDefinitions>
- <RowDefinition/>
- <RowDefinition/>
- </Grid.RowDefinitions>
- <Grid.ColumnDefinitions>
- <ColumnDefinition Width="885*"/>
- <ColumnDefinition Width="481*"/>
- </Grid.ColumnDefinitions>
- <StackPanel Grid.RowSpan="2">
- <TextBlock Style="{StaticResource HeaderTextStyle}" Margin="10" Foreground="Red"
- Text="论坛首页-DevDiv.com"/>
- <ListView x:Name="ForumList" Grid.RowSpan="2"
- ItemsSource="{Binding ForumItemList}"
- ItemTemplate="{StaticResource ForumListItemTemplate}"
- SelectionChanged="ListSelectionChanged" />
- </StackPanel>
- <StackPanel Orientation="Vertical" Grid.Column="1">
- <TextBlock Style="{StaticResource HeaderTextStyle}" Margin="10" Foreground="Red"
- Text="板块详情"/>
- <TextBlock Style="{StaticResource HeaderTextStyle}" Margin="10" FontSize="30"
- Text="{Binding ItemDetail}"/>
- </StackPanel>
- <StackPanel Orientation="Vertical" Grid.Column="1" Grid.Row="1" Background="White">
- <TextBlock Height="80"></TextBlock>
- <Image HorizontalAlignment="Center" Source="../Assets/icon.png"/>
- <TextBlock Height="135" FontSize="18" Foreground="Red">
- <Run Text="大家好!我是破船"/>
- <Run Text="欢迎跟我一起学习"/>
- <LineBreak/>
- <Run Text="Window 8 Metro App开发"/>
- </TextBlock>
- </StackPanel>
- </Grid>
- </Page>

- <ListView x:Name="ForumList" Grid.RowSpan="2"
- ItemsSource="{Binding ForumItemList}"
- ItemTemplate="{StaticResource ForumListItemTemplate}"
- SelectionChanged="ListSelectionChanged" />
- <StackPanel Orientation="Vertical" Grid.Column="1">
- <TextBlock Style="{StaticResource HeaderTextStyle}" Margin="10" Foreground="Red"
- Text="板块详情"/>
- <TextBlock Style="{StaticResource HeaderTextStyle}" Margin="10" FontSize="30"
- Text="{Binding ItemDetail}"/>
- </StackPanel>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。