当前位置:   article > 正文

Windows Store apps开发[7]视图模型与数据绑定_windows 视图模型

windows 视图模型

注:本系列学习帖子我在DevDiv.com移动开发社区原创首发

        转载请注明出处:BeyondVincent(破船)@DevDiv.com

如果你有什么问题也可以前往交流

下面是首发地址:

[DevDiv原创]Windows 8 Metro App开发Step by Step---(13个学习帖子)



    在程序中使用视图模型(ViewModel),可以带来很多好处,在开发中值得采纳,视图模型的使用对Metro App开发非常有帮助,通过学习MVC和MVVC你可以了解到试图模型。在这里我将介绍如何定义和使用试图模型,其中包括数据的绑定等内容。

    本次程序我以DevDiv论坛的板块为参考数据,写一个视图模型,有一个主画面,画面的左边有一个列表,列表中的数据来自试图模型中板块项列表,同时右边会显示选中板块的介绍。下面是程序的运行图,我们可以先来看看最终效果:



    本次学习内容主要包括一下几部分:

1、视图模型(ViewModel)的创建

2、添加页面

3、编写页面相关代码

4、添加资源字典

5、编写XAML

6、程序运行效果图与Demo程序


更多内容请查看下面的帖子


Windows 8 Metro App开发Step by Step

1、视图模型(ViewModel)的创建

   对于创建具有可持续性和和可维护性的应用程序,试图模型是必须具有的一个基础部分,它可以让我将应用程序数据与呈现数据给用户的方法相分离。如果不使用视图模型的话,你会发现你的程序越来越难以维护和开发。

   在本小节,我首先使用Blank App模版创建了一个名为DevDiv_DataBinding的工程。并在其中创建一个Data目录,然后再Data目录下创建两个新的类文件。分别是ForumItem.cs和ViewModel.cs文件。


ForumItem类的代码如下

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.ComponentModel;
  7. namespace DevDiv_DataBinding.Data
  8. {
  9.     class ForumItem : INotifyPropertyChanged
  10.     {
  11.         private string name, link, info;// 论坛板块的名称,链接和描述信息
  12.         private int topicCount; // 主题数
  13.         public string Name
  14.         {
  15.             get { return name; }
  16.             set { name = value; NotifyPropertyChanged("Name"); }
  17.         }
  18.         public string Link
  19.         {
  20.             get { return link; }
  21.             set { link = value; NotifyPropertyChanged("Link"); }
  22.         }
  23.         public string Info
  24.         {
  25.             get { return info; }
  26.             set { info = value; NotifyPropertyChanged("info"); }
  27.         }
  28.         public int TopicCount
  29.         {
  30.             get { return topicCount; }
  31.             set { topicCount = value; NotifyPropertyChanged("TopicCount"); }
  32.         }
  33.         public event PropertyChangedEventHandler PropertyChanged;
  34.         private void NotifyPropertyChanged(string propName)
  35.         {
  36.             if (PropertyChanged != null)
  37.             {
  38.                 PropertyChanged(this, new PropertyChangedEventArgs(propName));
  39.             }
  40.         }
  41.     }
  42. }


ForumItem类是论坛中每个板块的信息:板块名称、链 接、描述信息和主题数。
该类中最重要的部分是实现了INotifyPropertyChanged接口,即让该类的属性可观测,Metro UI控件一个很好的特性是它们支持数据绑定,这意味着当他们所显示的可观测数据发生变化时控件将会自动更新。所以在这里让 ForumItem支持可观测,那么方便UI上自动的进行更新。

ViewModel类的代码如下:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.ComponentModel;
  7. using System.Collections.ObjectModel;
  8. namespace DevDiv_DataBinding.Data
  9. {
  10.     class ViewModel : INotifyPropertyChanged
  11.     {
  12.         private ObservableCollection<ForumItem> forumItemList;
  13.         private int selectedItemIndex;
  14.         private string itemDetail;
  15.         public ViewModel()
  16.         {
  17.             forumItemList = new ObservableCollection<ForumItem>();
  18.             selectedItemIndex = -1;
  19.         }
  20.         public int SelectedItemIndex
  21.         {
  22.             get { return selectedItemIndex; }
  23.             set
  24.             {
  25.                 selectedItemIndex = value; NotifyPropertyChanged("SelectedItemIndex");
  26.             }
  27.         }
  28.         public string ItemDetail
  29.         {
  30.             get { return itemDetail; }
  31.             set
  32.             {
  33.                 itemDetail = value; NotifyPropertyChanged("ItemDetail");
  34.             }
  35.         }
  36.         public ObservableCollection<ForumItem> ForumItemList
  37.         {
  38.             get
  39.             {
  40.                 return forumItemList;
  41.             }
  42.         }
  43.         public event PropertyChangedEventHandler PropertyChanged;
  44.         private void NotifyPropertyChanged(string propName)
  45.         {
  46.             if (PropertyChanged != null)
  47.             {
  48.                 PropertyChanged(this, new PropertyChangedEventArgs(propName));
  49.             }
  50.         }
  51.     }
  52. }

    ViewModel中最重要的是 forumItemLi st对象集合(ObservableCollection)。ObservableCollection类实现了一个集合的基本特性,并在向列表中的项有被添加、删除或替换时发送事件通知。注意ObservableCollection类本身并不会发送一个事件通知,当它包含的某个对象的数据值被修改时,只有通过创建一个可观测的forumItemList 对象的可观测集合,才能确保对ForumItem所做的任何改变都将导致UI控件的更新。
     ViewModel也实现了 INotifyPropertyChanged接口,因为在这里有用到了可观测对象 itemDetail。

好吧,上面就是一个简单的视图模型,下面我会介绍视图模型如何跟UI进行交互以实现数据改变后UI能够自动更新。


2、添加页面
    我在工程中添加了Pages目录,并添加了一个空白页 ListPage.xaml。在这里我并没有使用工程默认创建的MainPage.xaml。
    为了让程序启动的时候默认加载 ListPage界面,需要 更新App.xaml.cs,如下语句,修改为Pages.ListPage
  1. var rootFrame = new Frame();
  2. if (!rootFrame.Navigate(typeof(Pages.ListPage)))
  3. {
  4.     throw new Exception("Failed to create initial page");
  5. }

这样我们的页面就添加好了。

下面我们就来对该页面 ListPage.xaml.cs进行编写

3、编写页面相关代码
这里我直接贴出 ListPage.xaml.cs文件的代码,以方便你直接阅读
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using Windows.Foundation;
  6. using Windows.Foundation.Collections;
  7. using Windows.UI.Xaml;
  8. using Windows.UI.Xaml.Controls;
  9. using Windows.UI.Xaml.Controls.Primitives;
  10. using Windows.UI.Xaml.Data;
  11. using Windows.UI.Xaml.Input;
  12. using Windows.UI.Xaml.Media;
  13. using Windows.UI.Xaml.Navigation;
  14. using DevDiv_DataBinding.Data;
  15. // 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>
  16. namespace DevDiv_DataBinding.Pages
  17. {
  18.     /// <summary>
  19.     /// An empty page that can be used on its own or navigated to within a Frame.
  20.     /// </summary>
  21.     public sealed partial class ListPage : Page
  22.     {
  23.         ViewModel viewModel;
  24.         public ListPage()
  25.         {
  26.             viewModel = new ViewModel();
  27.             viewModel.SelectedItemIndex = -1;
  28.             viewModel.ForumItemList.Add(new ForumItem { Name = "Android开发论坛", TopicCount = 4, Link = "http://www.devdiv.com/forum-110-1.html",
  29.                                                         Info = "Android开发论坛、Android开发者论坛、环境搭建、应用开发、驱动开发、系统移植、文档"});
  30.             viewModel.ForumItemList.Add(new ForumItem { Name = "Android开发资料", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html" });
  31.             viewModel.ForumItemList.Add(new ForumItem { Name = "iOS开发论坛/iPhone开发论坛", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html" });
  32.             viewModel.ForumItemList.Add(new ForumItem { Name = "iOS开发资料/iPhone开发资料", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html" });
  33.             viewModel.ForumItemList.Add(new ForumItem { Name = "微软/诺基亚 Windows Phone开发论坛 ", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html" });
  34.             viewModel.ForumItemList.Add(new ForumItem { Name = "Windows Phone开发资料", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html" });
  35.             viewModel.ForumItemList.Add(new ForumItem { Name = "Windows 8 开发论坛 ", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html",
  36.                                                         Info = "Windows 8 代码、教程、入门、文档、视频"});
  37.             viewModel.ForumItemList.Add(new ForumItem { Name = "Symbian开发论坛", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html" });
  38.             viewModel.ForumItemList.Add(new ForumItem { Name = "Symbian开发论坛", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html" });
  39.             viewModel.ForumItemList.Add(new ForumItem { Name = "Symbian开发论坛", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html" });
  40.             viewModel.ForumItemList.Add(new ForumItem { Name = "Symbian开发论坛", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html" });
  41.             viewModel.ForumItemList.Add(new ForumItem { Name = "Symbian开发论坛", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html" });
  42.             viewModel.ForumItemList.Add(new ForumItem { Name = "Symbian开发论坛", TopicCount = 8, Link = "http://www.devdiv.com/forum-102-1.html" });
  43.             this.InitializeComponent();
  44.             this.DataContext = viewModel;
  45.         }
  46.         /// <summary>
  47.         /// Invoked when this page is about to be displayed in a Frame.
  48.         /// </summary>
  49.         /// <param name="e">Event data that describes how this page was reached.  The Parameter
  50.         /// property is typically used to configure the page.</param>
  51.         protected override void OnNavigatedTo(NavigationEventArgs e)
  52.         {
  53.         }
  54.         private void ListSelectionChanged(object sender, SelectionChangedEventArgs e)
  55.         {
  56.             viewModel.ItemDetail = ((ForumItem)e.AddedItems[0]).Info;
  57.             if (viewModel.ItemDetail == null || viewModel.ItemDetail.Length == 0)
  58.             {
  59.                 viewModel.ItemDetail = ((ForumItem)e.AddedItems[0]).Name;
  60.             }
  61.         }
  62.     }
  63. }

上面的代码看着让我有点头疼,在这里我创建了一个viewModel并对其进行了初始化。你需要重点关注的下面的代码:
this.DataContext = viewModel;
DataContext 属性指定绑定到一个UI控件及其所有子控件的数据的来源。也就是说这里控件需要用到的数据来源是 viewModel。 使用this关键字来为整个布局设置DataContext。

代码最后定义了一个方法ListSelectionChanged,该方法处理当ListView中选择项改变后会触发的事件。在xaml文件中有使用到。

4、添加资源字典
     为了方便样式的统一,在这里我自定义了ListView使用到的一些样式,这样做的好处是UI控件的字体,颜色等属性我只需要在一个地方修改就可以应用到所有使用到的地方,非常的方便。为此我在工程中创建了Resources目录,并用Resource Dictionary(资源字典)项模板创建了一个新的ForumResourceDictionary.xaml文件。
该文件的代码如下:
  1. <ResourceDictionary
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4.     xmlns:local="using:DevDiv_DataBinding.Resources">
  5.     <ResourceDictionary.MergedDictionaries>
  6.         <ResourceDictionary Source="/Common/StandardStyles.xaml" />
  7.     </ResourceDictionary.MergedDictionaries>
  8.     <SolidColorBrush x:Key="AppBackgroundColor" Color="#3E790A"/>
  9.     <Style x:Key="ForumListItem" TargetType="TextBlock"
  10.            BasedOn="{StaticResource BasicTextStyle}" >
  11.         <Setter Property="FontSize" Value="38"/>
  12.         <Setter Property="FontWeight" Value="Light"/>
  13.         <Setter Property="Margin" Value="10, 0"/>
  14.         <Setter Property="VerticalAlignment" Value="Center"/>
  15.     </Style>
  16.     <DataTemplate x:Key="ForumListItemTemplate">
  17.         <StackPanel Orientation="Horizontal">
  18.             <TextBlock Text="{Binding Name}"
  19.                        Style="{StaticResource ForumListItem}"/>
  20.         </StackPanel>
  21.     </DataTemplate>
  22. </ResourceDictionary>

    看上面的代码,我定义了ForumListItem样式,以及一个数据模版ForumListItemTemplate。 ForumListItem定义了item的一些字体、布局等属性。 ForumListItemTemplate这定义了该item具有的控件内容以及绑定到的数据。 通过在.cs文件中设置DataContext属性,使视图模型作为绑定的数据源,Binding 关键字则让指定细节(“显示这个特定属性的值”)。

最后把该资源字典添加到App.xaml中即可,如下代码
<ResourceDictionary Source="Resources/ForumResourceDictionary.xaml"/>

5、编写XAML
我把ListPage.xaml文件的编写放到最后,这并不影响程序的开发。
同样我先把文件代码贴出来,然后对关键部分进行分析
  1. <Page
  2.     x:Class="DevDiv_DataBinding.Pages.ListPage"
  3.     IsTabStop="false"
  4.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  5.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  6.     xmlns:local="using:DevDiv_DataBinding.Pages"
  7.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  8.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  9.     mc:Ignorable="d">
  10.     <Grid Background="{StaticResource AppBackgroundColor}">
  11.         <Grid.RowDefinitions>
  12.             <RowDefinition/>
  13.             <RowDefinition/>
  14.         </Grid.RowDefinitions>
  15.         <Grid.ColumnDefinitions>
  16.             <ColumnDefinition Width="885*"/>
  17.             <ColumnDefinition Width="481*"/>
  18.         </Grid.ColumnDefinitions>
  19.         <StackPanel Grid.RowSpan="2">
  20.             <TextBlock Style="{StaticResource HeaderTextStyle}" Margin="10" Foreground="Red"
  21.                        Text="论坛首页-DevDiv.com"/>
  22.             <ListView x:Name="ForumList" Grid.RowSpan="2"
  23.                 ItemsSource="{Binding ForumItemList}"
  24.                 ItemTemplate="{StaticResource ForumListItemTemplate}"
  25.                 SelectionChanged="ListSelectionChanged" />
  26.         </StackPanel>
  27.         <StackPanel Orientation="Vertical" Grid.Column="1">
  28.             <TextBlock Style="{StaticResource HeaderTextStyle}" Margin="10" Foreground="Red"
  29.                        Text="板块详情"/>
  30.             <TextBlock Style="{StaticResource HeaderTextStyle}" Margin="10" FontSize="30"
  31.                        Text="{Binding ItemDetail}"/>
  32.         </StackPanel>
  33.         <StackPanel Orientation="Vertical" Grid.Column="1" Grid.Row="1" Background="White">
  34.     <TextBlock Height="80"></TextBlock>
  35.             <Image HorizontalAlignment="Center" Source="../Assets/icon.png"/>
  36.             <TextBlock Height="135" FontSize="18" Foreground="Red">        
  37.                 <Run Text="大家好!我是破船"/>
  38.                     <Run Text="欢迎跟我一起学习"/>  
  39.                 <LineBreak/>
  40.                     <Run Text="Window 8 Metro App开发"/>
  41.             </TextBlock>
  42.         </StackPanel>
  43.     </Grid>
  44. </Page>

首先,来看看VS设计器显示的内容是什么,如下图:



可以看到,Grid控件的Background 特性为我在资源字典中指定的颜色。

我们来看上面的关键代码:
  1. <ListView x:Name="ForumList" Grid.RowSpan="2"
  2.     ItemsSource="{Binding ForumItemList}"
  3.     ItemTemplate="{StaticResource ForumListItemTemplate}"
  4.     SelectionChanged="ListSelectionChanged" />

该代码片段是使用了ListView ,并指定了它的数据源ItemsSource和数据模板ItemTemplate。
Binding 关键字告诉ListView控件应该显示我在.cs代码文件中设置的DataContext对象的ForumItemList 属性的内容。而ItemTemplate则告诉ListView 控件应该如何显示ItemSource 中的每一数据项。StaticResource关键字和ForumListItemTemplate 值表示将使用我在资源字典中指定的数据模板。
最后就是指定SelectionChanged事件的处理方法。

再来看看下面的代码: 该代码是显示在画面右上角的,其中第二个TextBlock 中将数据源绑定到视图模型的ItemDetail上。当用户改变选择项时,视图模型中的ItemDetail 内容也会改变,这样UI也会自动的更新ItemDetail 内容。
  1. <StackPanel Orientation="Vertical" Grid.Column="1">
  2.     <TextBlock Style="{StaticResource HeaderTextStyle}" Margin="10" Foreground="Red"
  3.                 Text="板块详情"/>
  4.     <TextBlock Style="{StaticResource HeaderTextStyle}" Margin="10" FontSize="30"
  5.                 Text="{Binding ItemDetail}"/>
  6. </StackPanel>

至此,我们的代码关键部分就编写完毕了。在设计器中你是看不到ListView中的数据的,因为设计器不能显示动态生成的内容。下面就让我们运行起来看看吧。

6、程序运行效果图与Demo程序

未选中效果



选中效果



最后送上代码
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/243163
推荐阅读
相关标签
  

闽ICP备14008679号