原文: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. [TypeScript] Simplify asynchronous callback functions using async/await

    Learn how to write a promise based delay function and then use it in async await to see how much it ...

  2. arm-linux内存管理学习笔记(1)-内存页表的硬件原理

    linux kernel集中了世界顶尖程序猿们的编程智慧,犹记操作系统课上老师讲操作系统的四大功能:进程调度 内存管理 设备驱动 网络.从事嵌入式软件开发工作,对设备驱动和网络接触的比較多. 而进程调 ...

  3. webrtc 它android与PC互通

    折腾了一个多星期,今天终将PC和android音频,视频全部打通. 到现在,android与android,pC与PC,android与PC之间已经解决了互通,的音频和视频是能够. 前段时间开了PC与 ...

  4. _Decoder_Interface_init xxxxxx in amrFileCodec.o

    Undefined symbols for architecture arm64: "_Decoder_Interface_init", referenced from: Deco ...

  5. JQuery通过radio,select改变隐藏显示div

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/qq_36092584/article/details/52740681 1)select下拉框控制d ...

  6. 利用WPF建立自己的3d gis软件(非axhost方式)(七)实现简单的粒子效果

    原文:利用WPF建立自己的3d gis软件(非axhost方式)(七)实现简单的粒子效果 先下载SDK:https://pan.baidu.com/s/1M9kBS6ouUwLfrt0zV0bPew密 ...

  7. Java带参数的线程类ParameterizedThread——即如何给Thread传递参数

    在Java中似乎没有提供带运行参数的线程实现类,在第三方类库中也没有找到.网上有大量的文章在讨论这个问题,但都没有提供很好的代码封装解决方案,这令我很吃惊.如果读者知道有官方或者第三方的实现方式,欢迎 ...

  8. js typeof instanceof

    一般都是用typeof推断变量存在 例如if(typeof a!="undefined"){}.不是要去使用if(a)因为假定a不存在(未申报)将是错误的. 由于typeof经验n ...

  9. GammaRay is a tool to poke around in a Qt-application(确实很多功能)

    GammaRay is a tool to poke around in a Qt-application and also to manipulate the application to some ...

  10. angular中通过$location获取路径(参数)的写法

    以下获取与修改的 URL 以  ( http://172.16.0.88:8100/#/homePage?id=10&a=100  ) 为例 [一]获取 (不修改URL) //1.获取当前完整 ...