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

简介: 原文:WPF MvvmLight简单实例(1) 页面导航实现了那些功能,先看看截图:   操作描述: 在程序运行后,点击“Load”按钮,页面会加载PageOne,点击PageOne页面中的“Next”按钮即可进入PageTwo页面, 点击PageTwo页面中的“Next”即可进...
原文: 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="1" Foreground="White" FontSize="30"></TextBlock>
        <StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
            <TextBlock Text="{Binding Title}" FontSize="18" Foreground="White"></TextBlock>
            <Button Width="80" Height="20" Content="Click me!!!" Margin="0,20,0,0" Command="{Binding ChangeCommand}"></Button>
        </StackPanel>
        <Button Command="{Binding GoToNextCommand}"  Content="Next" Width="60" Height="30" 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 > 1)
            {
                _historic.RemoveAt(_historic.Count - 1);
               
                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 < 1)
            {
                return null;
            }

            for (var i = 0; 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

 

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

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

 

目录
相关文章
|
16天前
|
编译器 C# Windows
一个基于Net Core3.0的WPF框架Hello World实例
一个基于Net Core3.0的WPF框架Hello World实例
WPF界面异常:未将对象引用设置到对象实例
WPF界面异常:未将对象引用设置到对象实例
|
C# 前端开发
WPF中的多进程(Threading)处理实例(一)
原文:WPF中的多进程(Threading)处理实例(一) 说明:希望通过揣摩这些案例,能进一步了解进程的工作原理。 1.方法一描述的是在同一窗口中,在计算素数的同时而不影响Canvas的工作。 方法1 1 #region Long-Running Calculat...
1539 0
|
Java C#
WPF防止重复运行实例
原文:WPF防止重复运行实例 1、方法一 在app.xaml.cs下添加如下代码: /// /// App.xaml 的交互逻辑 /// public partial class App : Application { System.
1166 0
|
API C# Windows
WPF 利用键盘钩子来捕获键盘,做一些不为人知的事情...完整实例
原文:WPF 利用键盘钩子来捕获键盘,做一些不为人知的事情...完整实例 键盘钩子是一种可以监控键盘操作的指令。 看到这句话是不是觉得其实键盘钩子可以做很多事情.   场景 当你的程序需要一个全局的快捷键时,可以考虑使用键盘钩子,如大家常用qq的截图快捷键,那么在WPF里怎么去实现呢? 当...
1420 0
|
区块链 C#
WPF如何实现一个漂亮的页签导航UI
原文:WPF如何实现一个漂亮的页签导航UI      最近看到一个比较漂亮的UI主界面,该UI是用左边的页签进行导航,比较有特色,就想着尝试用WPF来实现一下。经过一番尝试,基本上将UI设计图的效果用WPF程序进行了实现。
2124 0
|
前端开发 C#
silverlight,WPF动画终极攻略之番外 3D切换导航篇(Blend 4开发)
原文:silverlight,WPF动画终极攻略之番外 3D切换导航篇(Blend 4开发) 这篇介绍的是3D导航,点击图标,页面360°翻转的效果!有什么不足的欢迎大家指出来。 1.新建一个usercontrol,命名为menu. 2.按照下图设置一下属性。
1225 0
|
C# 索引
WPF中元素拖拽的两个实例
原文:WPF中元素拖拽的两个实例   今天结合之前做过的一些拖拽的例子来对这个方面进行一些总结,这里主要用两个例子来说明在WPF中如何使用拖拽进行操作,元素拖拽是一个常见的操作,第一个拖拽的例子是将ListBox中的子元素拖拽到ListView的某一个节点,从而将该子元素作为当前节点的子节点。
1141 0
|
C#
潜移默化学会WPF(绚丽篇)--热烈欢迎RadioButton,改造成功,改造成ImageButton,新版导航
原文:潜移默化学会WPF(绚丽篇)--热烈欢迎RadioButton,改造成功,改造成ImageButton,新版导航 本样式 含有  触发器 和 动画    模板  ,多条件触发器,还有布局   本人博客园地址  http://www.
1622 0
|
C#
WPF和Expression Blend开发实例:Adorner(装饰器)应用实例
原文:WPF和Expression Blend开发实例:Adorner(装饰器)应用实例 装饰器-- 表示用于修饰 UIElement 的 FrameworkElement 的抽象类 简单来说就是,在不改变一个UIElement结构的情况下,将一个Visual对象加到它上面.
1007 0