C# Prism 框架使用(八) 导航

8 篇文章 0 订阅

Prism(八) 导航

源码地址 - WineMonk/PrismStudy: Prism框架学习 (github.com)

导航基础

视图

ViewA/B.xaml

<UserControl x:Class="ModuleA.Views.ViewA"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:prism="http://prismlibrary.com/"             
             prism:ViewModelLocator.AutoWireViewModel="True">
    <StackPanel>
        <TextBlock Text="{Binding Title}" FontSize="48" HorizontalAlignment="Center" VerticalAlignment="Center" />
        <TextBlock Text="{Binding PageViews}" FontSize="24" HorizontalAlignment="Center" VerticalAlignment="Center"/>
    </StackPanel>
</UserControl>

ViewA/BViewModel.cs

public class ViewAViewModel : BindableBase
{
    public ViewAViewModel()
    {

    }
}

注册导航视图

public class ModuleAModule : IModule
{
    public void OnInitialized(IContainerProvider containerProvider)
    {
        
    }

    public void RegisterTypes(IContainerRegistry containerRegistry)
    {
        containerRegistry.RegisterForNavigation<ViewA>();
        containerRegistry.RegisterForNavigation<ViewB>();
    }
}

public partial class App : PrismApplication
{
    protected override Window CreateShell()
    {
        return Container.Resolve<MainWindow>();
    }

    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        
    }

    protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
    {
        moduleCatalog.AddModule<ModuleA.ModuleAModule>();
    }
}

导航视图

MainWindow.xaml

<Window x:Class="BasicRegionNavigation.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="True"
        Title="{Binding Title}" Height="350" Width="525">
    <DockPanel LastChildFill="True">
        <StackPanel Orientation="Horizontal" DockPanel.Dock="Top" Margin="5" >
            <Button Command="{Binding NavigateCommand}" CommandParameter="ViewA" Margin="5">Navigate to View A</Button>
            <Button Command="{Binding NavigateCommand}" CommandParameter="ViewB" Margin="5">Navigate to View B</Button>
        </StackPanel>
        <ContentControl prism:RegionManager.RegionName="ContentRegion" Margin="5"  />
    </DockPanel>
</Window>

MainWindowViewModel.cs

public class MainWindowViewModel : BindableBase
{
    private readonly IRegionManager _regionManager;

    private string _title = "Prism Unity Application";
    public string Title
    {
        get { return _title; }
        set { SetProperty(ref _title, value); }
    }

    public DelegateCommand<string> NavigateCommand { get; private set; }

    public MainWindowViewModel(IRegionManager regionManager)
    {
        _regionManager = regionManager;

        NavigateCommand = new DelegateCommand<string>(Navigate);
    }

    private void Navigate(string navigatePath)
    {
        if (navigatePath != null)
            _regionManager.RequestNavigate("ContentRegion", navigatePath);
    }
}

导航视图请求回调

MainWindowViewModel.cs

public class MainWindowViewModel : BindableBase
{
    private readonly IRegionManager _regionManager;

    private string _title = "Prism Unity Application";
    public string Title
    {
        get { return _title; }
        set { SetProperty(ref _title, value); }
    }

    public DelegateCommand<string> NavigateCommand { get; private set; }

    public MainWindowViewModel(IRegionManager regionManager)
    {
        _regionManager = regionManager;

        NavigateCommand = new DelegateCommand<string>(Navigate);
    }

    private void Navigate(string navigatePath)
    {
        if (navigatePath != null)
            // _regionManager.RequestNavigate("ContentRegion", navigatePath);
            _regionManager.RequestNavigate("ContentRegion", navigatePath, NavigationComplete);
    }
	
    /// <summary>
    /// 导航请求回调方法
    /// </summary>
    /// <param name="result">导航结果</param>
    private void NavigationComplete(NavigationResult result)
    {
        System.Windows.MessageBox.Show(String.Format("Navigation to {0} complete. ", result.Context.Uri));
    }
}

视图察觉参与导航

ViewA/B.xaml

<UserControl x:Class="ModuleA.Views.ViewA"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:prism="http://prismlibrary.com/"             
             prism:ViewModelLocator.AutoWireViewModel="True">
    <StackPanel>
        <TextBlock Text="{Binding Title}" FontSize="48" HorizontalAlignment="Center" VerticalAlignment="Center" />
        <TextBlock Text="{Binding PageViews}" FontSize="24" HorizontalAlignment="Center" VerticalAlignment="Center"/>
    </StackPanel>
</UserControl>

ViewA/BViewModel.cs

public class ViewAViewModel : BindableBase, INavigationAware
{
    private string _title = "ViewA";
    public string Title
    {
        get { return _title; }
        set { SetProperty(ref _title, value); }
    }

    private int _pageViews;
    public int PageViews
    {
        get { return _pageViews; }
        set { SetProperty(ref _pageViews, value); }
    }

    public ViewAViewModel()
    {

    }

    /// <summary>
    /// 当实现者被导航到时调用。
    /// </summary>
    /// <param name="navigationContext">导航上下文</param>
    public void OnNavigatedTo(NavigationContext navigationContext)
    {
        PageViews++;
    }

    /// <summary>
    /// 调用以确定此实例是否可以处理导航请求。
    /// </summary>
    /// <param name="navigationContext">导航上下文</param>
    /// <returns>如果这个实例接受导航请求,返回True;否则,False(将会导航至此视图的新实例)</returns>
    public bool IsNavigationTarget(NavigationContext navigationContext)
    {
        return true;
    }

    /// <summary>
    /// 当实现者被导航离开时调用。
    /// </summary>
    /// <param name="navigationContext">导航上下文</param>
    public void OnNavigatedFrom(NavigationContext navigationContext)
    {

    }
}

通过参数导航

Model

Person.cs

public class Person : INotifyPropertyChanged
{
    #region Properties

    private string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            _firstName = value;
            OnPropertyChanged();
        }
    }

    private string _lastName;
    public string LastName
    {
        get { return _lastName; }
        set
        {
            _lastName = value;
            OnPropertyChanged();
        }
    }

    private int _age;
    public int Age
    {
        get { return _age; }
        set
        {
            _age = value;
            OnPropertyChanged();
        }
    }

    private DateTime? _lastUpdated;
    public DateTime? LastUpdated
    {
        get { return _lastUpdated; }
        set
        {
            _lastUpdated = value;
            OnPropertyChanged();
        }
    }

    #endregion //Properties

    #region INotifyPropertyChanged

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged([CallerMemberName]string propertyname = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyname));
    }

    #endregion //INotifyPropertyChanged

    public override string ToString()
    {
        return String.Format("{0}, {1}", LastName, FirstName);
    }
}

View

PersonList.xaml

<UserControl
    x:Class="ModuleA.Views.PersonList"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
    xmlns:prism="http://prismlibrary.com/"
    prism:ViewModelLocator.AutoWireViewModel="True">

    <UserControl.Resources>
        <Style TargetType="TabItem">
            <Setter Property="Header" Value="{Binding DataContext.SelectedPerson.FirstName}" />
        </Style>
    </UserControl.Resources>

    <Grid
        x:Name="LayoutRoot"
        Margin="10"
        Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="100" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>

        <ListBox x:Name="_listOfPeople" ItemsSource="{Binding People}">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="SelectionChanged">
                    <prism:InvokeCommandAction Command="{Binding PersonSelectedCommand}" CommandParameter="{Binding SelectedItem, ElementName=_listOfPeople}" />
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </ListBox>
        <TabControl
            Grid.Row="1"
            Margin="10"
            prism:RegionManager.RegionName="PersonDetailsRegion" />
    </Grid>
</UserControl>

PersonDetail.xaml

<UserControl x:Class="ModuleA.Views.PersonDetail"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:prism="http://prismlibrary.com/"             
             prism:ViewModelLocator.AutoWireViewModel="True">
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <!-- First Name -->
        <TextBlock Text="First Name:" Margin="5" />
        <TextBlock Grid.Column="1" Margin="5" Text="{Binding SelectedPerson.FirstName}" />

        <!-- Last Name -->
        <TextBlock Grid.Row="1" Text="Last Name:" Margin="5" />
        <TextBlock Grid.Row="1" Grid.Column="1"  Margin="5" Text="{Binding SelectedPerson.LastName}" />

        <!-- Age -->
        <TextBlock Grid.Row="2" Text="Age:" Margin="5"/>
        <TextBlock Grid.Row="2" Grid.Column="1"  Margin="5" Text="{Binding SelectedPerson.Age}"/>
    </Grid>
</UserControl>

ViewModel

PersonListViewModel.cs

using System;
using ModuleA.Business;
using Prism.Mvvm;
using Prism.Navigation.Regions;

namespace ModuleA.ViewModels
{
    public class PersonDetailViewModel : BindableBase, INavigationAware
    {
        private Person _selectedPerson;
        public Person SelectedPerson
        {
            get { return _selectedPerson; }
            set { SetProperty(ref _selectedPerson, value); }
        }

        public PersonDetailViewModel()
        {

        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            var person = navigationContext.Parameters["person"] as Person;
            if (person != null)
                SelectedPerson = person;
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            var person = navigationContext.Parameters["person"] as Person;
            if (person != null)
                return SelectedPerson != null && SelectedPerson.LastName == person.LastName;
            else
                return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {

        }
    }
}

PersonDetailViewModel.cs

using ModuleA.Business;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation.Regions;
using System;
using System.Collections.ObjectModel;

namespace ModuleA.ViewModels
{
    public class PersonListViewModel : BindableBase
    {
        IRegionManager _regionManager;

        private ObservableCollection<Person> _people;
        public ObservableCollection<Person> People
        {
            get { return _people; }
            set { SetProperty(ref _people, value); }
        }

        public DelegateCommand<Person> PersonSelectedCommand { get; private set; }

        public PersonListViewModel(IRegionManager regionManager)
        {
            _regionManager = regionManager;

            PersonSelectedCommand = new DelegateCommand<Person>(PersonSelected);
            CreatePeople();
        }

        private void PersonSelected(Person person)
        {
            var parameters = new NavigationParameters();
            parameters.Add("person", person);

            if (person != null)
                __regionManager.RequestNavigate("PersonDetailsRegion", typeof(PersonDetail).Name, parameters);
        }

        private void CreatePeople()
        {
            var people = new ObservableCollection<Person>();
            for (int i = 0; i < 10; i++)
            {
                people.Add(new Person()
                {
                    FirstName = String.Format("First {0}", i),
                    LastName = String.Format("Last {0}", i),
                    Age = i
                });
            }

            People = people;
        }
    }
}

导航请求处理

ViewA/BViewModel.cs

public class ViewAViewModel : BindableBase, IConfirmNavigationRequest
{
    public ViewAViewModel()
    {

    }

    /// <summary>
    /// 确定此实例是否接受导航。
    /// </summary>
    /// <param name="navigationContext">导航上下文</param>
    /// <param name="continuationCallback">指示导航何时可以继续的回调函数。</param>
    /// <remarks>
    /// 此方法的实现者在此方法完成之前不需要调用回调函数,但它们必须确保回调函数最终被调用。
    /// </remarks>
    public void ConfirmNavigationRequest(NavigationContext navigationContext, Action<bool> continuationCallback)
    {
        bool result = true;

        if (MessageBox.Show("Do you to navigate?", "Navigate?", MessageBoxButton.YesNo) == MessageBoxResult.No)
            result = false;

        continuationCallback(result);
    }

    public bool IsNavigationTarget(NavigationContext navigationContext)
    {
        return true;
    }

    public void OnNavigatedFrom(NavigationContext navigationContext)
    {
        
    }

    public void OnNavigatedTo(NavigationContext navigationContext)
    {
        
    }
}
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: WPF Prism框架是一个面向对象的框架,用于开发模块化、可扩展的WPF应用程序,它基于MVVM设计模式和依赖注入技术。该框架的主要目的是能够轻松地实现可插拔的模块,公共的服务、组件和工具类的共享,同时也提供了灵活的路由、事件聚合、模块加载、导航和命令处理等机制。使用WPF Prism框架可以快速地开发出灵活的WPF应用程序,从而提高代码质量和开发效率,减少代码的维护难度。 WPF Prism框架具有以下的特点: 1. 扩展性:可以轻松地添加新的模块、服务和组件,同时也可以快速替换现有的组件。 2. 可重用性:提供了丰富的公共组件、服务和工具类,从而可以提高代码的可重用性。 3. 灵活性:提供了灵活的路由、事件聚合、模块加载和导航等机制,能够更好地满足应用程序的需求。 4. 易用性:提供了一套完整的MVVM设计模式和依赖注入技术的实践方案,从而能够更好地组织应用程序的逻辑。 总之,WPF Prism框架是一个强大的工具,能够让我们更好地开发WPF应用程序,提高代码质量和开发效率,实现可插拔的模块化和可扩展性,同时也具有灵活性和易用性。 ### 回答2: WPF Prism框架是一种面向MVVM模式的开源框架,它帮助开发人员使用模块化的方式构建可扩展、可重用和易于维护的WPF应用程序。该框架主要由Microsoft和模式仲裁者团队开发和维护,它借鉴了许多现代的软件开发理念,比如IoC容器、依赖注入和事件聚合器等。 WPF Prism框架的核心思想是将应用程序分解为许多可独立维护和扩展的模块。这些模块可以基于业务逻辑、UI、数据或任何其他特征进行分组。在该框架中,模块由各种名为“组件”的构建块组成。这些组件包括视图(View)、视图模型(ViewModel)、服务(Service)、模型(Model)等。通过基于这些组件的开发,可以实现具有高度可伸缩性和可重用性的应用程序。 为了实现这种模块化开发和组件化架构,WPF Prism框架提供了一些重要的工具和特性。例如,在该框架中可以使用依赖注入容器(如Unity)来管理组件及其依赖关系。此外,该框架还提供了一些基于事件的消息机制,可方便地实现模块间的交互和通信。 总体来说,WPF Prism框架是一种利用开源技术实现企业级应用程序开发的最佳选择。它具有良好的模块化、组件化和可扩展性特性,可以在实现复杂WPF应用程序时提高开发效率和代码质量。 ### 回答3: WPF Prism是一个基于WPF框架,它为大型应用程序提供了一种组织、设计和部署的方式。它旨在帮助开发者构建可扩展、可维护和可测试的WPF应用程序。 WPF Prism采用了面向模块的编程思想,它将整个应用程序划分为多个模块,每个模块都包含自己的逻辑和用户界面。这种模块化设计使得应用程序易于扩展和维护,同时也简化了开发流程。 WPF Prism同时提供了一组强大的工具和功能,如依赖注入、命令模式和事件聚合等,这些功能让WPF应用程序更加易于开发和测试。它还提供了一个强大的导航和区域管理系统,开发者可以使用这些系统来管理不同部分的用户界面和功能。 总之,WPF Prism是一个优秀的框架,它为开发者提供了全面的工具和功能,使得构建WPF应用程序变得更加容易和高效。它的结构良好、可扩展性强,而且可以充分利用WPF的强大功能。无论是大型企业应用程序还是小型桌面应用程序,WPF Prism都是一个理想的选择。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值