原文:WPF MvvmLight简单实例(1) 页面导航

实现了那些功能,先看看截图:

操作描述:

在程序运行后,点击“Load”按钮,页面会加载PageOne,点击PageOne页面中的“Next”按钮即可进入PageTwo页面,

点击PageTwo页面中的“Next”即可进入PageThree页面,点击Back可返回Page1页面

第一步:新建工程并使用NuGet安装MvvmLight

第二步:添加Views文件夹并添加相应的ViewModel

本文主要描述如何使用MvvmLight实现简单的导航效果,所以页面基本上都是大同小异比较简单ViewModel也比较简单,所以这里只PageOne.xaml以及PageOneViewModel.cs

PageOne.xaml代码:

<Page x:Class="MvvmLightSample.Views.PageOne"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:MvvmLightSample.Views"
mc:Ignorable="d" Title="PageOne">
<Page.DataContext>
<Binding Path="PageOne" Source="{StaticResource Locator}"></Binding>
</Page.DataContext>
<Grid Background="Orange">
<TextBlock Text="" Foreground="White" FontSize=""></TextBlock>
<StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
<TextBlock Text="{Binding Title}" FontSize="" Foreground="White"></TextBlock>
<Button Width="" Height="" Content="Click me!!!" Margin="0,20,0,0" Command="{Binding ChangeCommand}"></Button>
</StackPanel>
<Button Command="{Binding GoToNextCommand}" Content="Next" Width="" Height="" VerticalAlignment="Bottom" HorizontalAlignment="Right" Margin="0,0,10,10"></Button>
</Grid>
</Page>

PageOneViewModel.cs代码:

  public class PageOneViewModel : ViewModelBase
{
private INavigationService _navigationService;
public ICommand GoBackCommand { get; set; }
public ICommand GoToNextCommand { get; set; }
public ICommand ChangeCommand { get; set;}
private string _title; public string Title
{
get { return _title; }
set
{
Set(()=>Title,ref _title,value);
}
} public PageOneViewModel(INavigationService navigationService)
{
_navigationService = navigationService;
Title = "Please Click me!";
GoBackCommand = new RelayCommand(GoBack);
GoToNextCommand = new RelayCommand(GotoNext);
ChangeCommand = new RelayCommand(ChangeTitle);
}
private void ChangeTitle()
{
Title = "Hello MvvmLight!!!";
}
private void GoBack()
{
_navigationService.GoBack();
}
private void GotoNext()
{
var navigationService = ServiceLocator.Current.GetInstance<INavigationService>();
navigationService.NavigateTo("PageTwo2");
}
}

第三步:修改ViewModelLocator.cs

 public class ViewModelLocator
{
/// <summary>
/// Initializes a new instance of the ViewModelLocator class.
/// </summary>
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<PageOneViewModel>();
SimpleIoc.Default.Register<PageTwoViewModel>();
SimpleIoc.Default.Register<PageThreeViewModel>();
SimpleIoc.Default.Register<PageFourViewModel>(); var navigationService = this.CreateNavigationService();
SimpleIoc.Default.Register<INavigationService>(() => navigationService);
}
private INavigationService CreateNavigationService()
{
var nav = new NavigationService(); var navigationService = new NavigationService();
navigationService.Configure("PageTwo1", new Uri("/MvvmLightSample;component/Views/PageOne.xaml", UriKind.Relative));
navigationService.Configure("PageTwo2", new Uri("/MvvmLightSample;component/Views/PageTwo.xaml", UriKind.Relative));
navigationService.Configure("PageTwo3", new Uri("/MvvmLightSample;component/Views/PageThree.xaml", UriKind.Relative));
navigationService.Configure("PageTwo4", new Uri("/MvvmLightSample;component/Views/PageFour.xaml", UriKind.Relative));
return navigationService;
}
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
public PageOneViewModel PageOne
{
get
{
return ServiceLocator.Current.GetInstance<PageOneViewModel>();
}
}
public PageTwoViewModel PageTwo
{
get
{
return ServiceLocator.Current.GetInstance<PageTwoViewModel>();
}
}
public PageThreeViewModel PageThree
{
get
{
return ServiceLocator.Current.GetInstance<PageThreeViewModel>();
}
}
public PageFourViewModel PageFour
{
get
{
return ServiceLocator.Current.GetInstance<PageFourViewModel>();
}
}
public static void Cleanup()
{
}
}

NavigationService.cs代码:

 public class NavigationService : ViewModelBase,INavigationService
{
private readonly Dictionary<string, Uri> _pagesByKey;
private readonly List<string> _historic;
private string _currentPageKey;
#region Properties
public string CurrentPageKey
{
get
{
return _currentPageKey;
} private set
{
Set(()=>CurrentPageKey,ref _currentPageKey,value);
}
}
public object Parameter { get; private set; }
#endregion
#region Ctors and Methods
public NavigationService()
{
_pagesByKey = new Dictionary<string, Uri>();
_historic = new List<string>();
}
public void GoBack()
{
if (_historic.Count > )
{
_historic.RemoveAt(_historic.Count - ); NavigateTo(_historic.Last(), "Back");
}
}
public void NavigateTo(string pageKey)
{
NavigateTo(pageKey, "Next");
} public virtual void NavigateTo(string pageKey, object parameter)
{
lock (_pagesByKey)
{
if (!_pagesByKey.ContainsKey(pageKey))
{
throw new ArgumentException(string.Format("No such page: {0} ", pageKey), "pageKey");
} var frame = GetDescendantFromName(Application.Current.MainWindow, "MainFrame") as Frame; if (frame != null)
{
frame.Source = _pagesByKey[pageKey];
}
Parameter = parameter;
if (parameter.ToString().Equals("Next"))
{
_historic.Add(pageKey);
}
CurrentPageKey = pageKey;
}
} public void Configure(string key, Uri pageType)
{
lock (_pagesByKey)
{
if (_pagesByKey.ContainsKey(key))
{
_pagesByKey[key] = pageType;
}
else
{
_pagesByKey.Add(key, pageType);
}
}
} private static FrameworkElement GetDescendantFromName(DependencyObject parent, string name)
{
var count = VisualTreeHelper.GetChildrenCount(parent); if (count < )
{
return null;
} for (var i = ; i < count; i++)
{
var frameworkElement = VisualTreeHelper.GetChild(parent, i) as FrameworkElement;
if (frameworkElement != null)
{
if (frameworkElement.Name == name)
{
return frameworkElement;
} frameworkElement = GetDescendantFromName(frameworkElement, name);
if (frameworkElement != null)
{
return frameworkElement;
}
}
}
return null;
} #endregion
}

源码下载地址:http://download.csdn.net/detail/qindongshou1/9481969

此文仅作学习中的记录,希望对看到此文的同学有一点点的帮助。

文中如果有不正确的地方欢迎指正。

WPF MvvmLight简单实例(1) 页面导航的更多相关文章

  1. 【转】【WPF】WPF MVVM 简单实例

    1 新建WPF 应用程序WPFMVVMExample 程序结构如下图所示. 2 Model实现 在Model文件夹下新建业务类StudentModel(类文件StudentModel.cs),类的详细 ...

  2. 梦琪小生 【转】【WPF】WPF MVVM 简单实例

    1 新建WPF 应用程序WPFMVVMExample 程序结构如下图所示. 2 Model实现 在Model文件夹下新建业务类StudentModel(类文件StudentModel.cs),类的详细 ...

  3. Wpf(Storyboard)动画简单实例

    原文:Wpf(Storyboard)动画简单实例 动画的三种变换方式 RotateTransform:旋转变换变化值:CenterX围绕转的圆心横坐标 CenterY纵坐标 Angle旋转角度(角度正 ...

  4. WPF的页面导航

    工作中之前接触过的WPF程序一直是使用TabControl作不同页面间的切换,每个Tab负责独立的功能,清晰简捷,所以一直就没有动力研究WPF自带的页面导航.(虽然接触过使用页面导航的WPF项目,也并 ...

  5. TERSUS无代码开发(笔记06)-简单实例手机端页面设计

    手机端的设计 1.页面说明 2.默认页面===>提交请假单(上面页面双击进入,页面主要编辑区) 2.1默认页面===>提交请假单===>头部区(页面部份主要编辑区01) 2.1.1默 ...

  6. TERSUS无代码开发(笔记05)-简单实例电脑端页面设计

    案例笔记电脑端页面设计   1.新建项目(请假管理qjgl)   2.开发软件界面介绍(常用的功能按键)      3.目录中显示元件对象      4.对元件对象的操作主要方式是双击(双击哪个元件, ...

  7. WinPhone学习笔记(一)——页面导航与页面相关

    最近学一下Windows Phone(接下来简称“WinPhone”)的开发,在很久很久前稍探究一下WinPhone中对一些传感器的开发,那么现在就从头来学学WinPhone的开发.先从WinPhon ...

  8. 【Win10】页面导航的实现

    注:本文基于 Windows 10 10240 及其 SDK 编写,若以后有变化,请以新版本为准. 页面导航我们是再熟悉不过了,浏览器.手机 App 大多都使用这种方式来展示内容.在 Windows ...

  9. 简单实例一步一步帮你搞清楚MVC3中的路由以及区域

    我们都知道MVC 3 程序的所有请求都是先经过路由解析然后分配到特定的Controller 以及 Action 中的,为什么这些知识讲完了Controller Action Model 后再讲呢?这个 ...

随机推荐

  1. springmvc使用和经验总结(长沙师说网络科技有限公司)

    springmvc 先分析下代码,高速学习.先要把配置文件写好, 给上2个类详细看看 package com.shishuo.studio.action; import org.apache.log4 ...

  2. .net程序客户端更新方案

    原文:.net程序客户端更新方案 客户端程序一个很大的不便的地方就是程序集更新,本文这里简单的介绍一种通用的客户端更新方案.这个方案依赖程序集的动态加载,具体方案如下: 将程序集存储在一个文件数据库中 ...

  3. tomcat7,8 centos7 配置apr极好教程

    转自:http://blog.csdn.net/remote_roamer/article/details/51719891 第一次我自己是用的yum安装apr, apr-utils, tomcat- ...

  4. Node.js,一生所爱

    下午参加了<云品秀--前端前沿>,用友云平台前端架构师郭永峰(站着的那位)讲得很棒,而我最关注的就是Node了.最后我问了他关于独立开发,后端选择Node还是别的语言.他讲了很多,说自己在 ...

  5. QT5.8.0+MSVC2015安装以及环境配置(不需要安装VS2015)

    原文:QT5.8.0+MSVC2015安装以及环境配置(不需要安装VS2015) 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/snow_rain_ ...

  6. Maven打包不打test,Maven中-DskipTests和-Dmaven.test.skip=true的区别

    在使用mvn package进行编译.打包时,Maven会执行src/test/java中的JUnit测试用例, 有时为了跳过测试,会使用参数-DskipTests和-Dmaven.test.skip ...

  7. Visual Studio - 为默认模板添加版权信息

    转自:http://www.cnblogs.com/easyzikai/archive/2012/10/14/2723328.html 和 http://www.cnblogs.com/eagle19 ...

  8. misc子系统

    跟着内核学框架-从misc子系统到3+2+1设备识别驱动框架   misc子系统在Linux中是一个非常简单的子系统,但是其清晰的框架结构非常适合用来研究设备识别模型.本文从misc子系统的使用出发, ...

  9. 链接hdf5库出现错误的解决办法

    作者:朱金灿 来源:http://blog.csdn.net/clever101 在链接hdf5库出现一些链接错误: error LNK2001: 无法解析的外部符号 _H5T_NATIVE_DOUB ...

  10. Linux命令list

    文件和目录 cd /home 进入 '/ home' 目录' cd .. 返回上一级目录 cd ../.. 返回上两级目录 cd 进入个人的主目录 cd ~user1 进入个人的主目录 cd - 返回 ...