环境:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<ProduceReferenceAssembly>true</ProduceReferenceAssembly>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebugType>portable</DebugType>
<DebugSymbols>true</DebugSymbols>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Prism.DryIoc.Forms" Version="8.1.97" />
<PackageReference Include="Xamarin.Forms" Version="5.0.0.2196" />
<PackageReference Include="Xamarin.Essentials" Version="1.7.0" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="Views\MainPage.xaml">
<Generator>MSBuild:UpdateDesignTimeXaml</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Views\ViewA.xaml">
<Generator>MSBuild:UpdateDesignTimeXaml</Generator>
</EmbeddedResource>
<EmbeddedResource Update="Views\ViewB.xaml">
<Generator>MSBuild:UpdateDesignTimeXaml</Generator>
</EmbeddedResource>
</ItemGroup>
</Project>
配置,IOC:
<?xml version="1.0" encoding="utf-8" ?>
<prism:PrismApplication
x:Class="MyXamarin11.App"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:prism="http://prismlibrary.com"
mc:Ignorable="d">
<Application.Resources>
<Color x:Key="PrimaryColor">#7E7D81</Color>
<Color x:Key="AccentColor">#00A5F2</Color>
<Color x:Key="TextColor">White</Color>
<Style TargetType="TabbedPage">
<Setter Property="BarBackgroundColor" Value="{StaticResource PrimaryColor}" />
<Setter Property="BarTextColor" Value="{StaticResource TextColor}" />
<Setter Property="SelectedTabColor" Value="{StaticResource AccentColor}" />
<Setter Property="UnselectedTabColor" Value="{StaticResource PrimaryColor}" />
</Style>
<Style TargetType="NavigationPage">
<Setter Property="BarBackgroundColor" Value="{StaticResource PrimaryColor}" />
<Setter Property="BarTextColor" Value="{StaticResource TextColor}" />
</Style>
<Style TargetType="Button">
<Setter Property="BackgroundColor" Value="{StaticResource AccentColor}" />
<Setter Property="TextColor" Value="{StaticResource TextColor}" />
<Setter Property="CornerRadius" Value="15" />
</Style>
<Style x:Key="DarkButton" TargetType="Button">
<Setter Property="BackgroundColor" Value="{StaticResource PrimaryColor}" />
<Setter Property="TextColor" Value="{StaticResource TextColor}" />
<Setter Property="CornerRadius" Value="15" />
</Style>
</Application.Resources>
</prism:PrismApplication>
using System;
using Prism.Ioc;
using MyXamarin11.ViewModels;
using MyXamarin11.Views;
using Xamarin.Forms;
using MyXamarin11.Services;
namespace MyXamarin11
{
public partial class App
{
public App()
{
}
protected override async void OnInitialized()
{
InitializeComponent();
var result = await NavigationService.NavigateAsync("MainPage");
if (!result.Success)
{
System.Diagnostics.Debugger.Break();
}
}
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
//导航注册
containerRegistry.RegisterForNavigation<NavigationPage>();
containerRegistry.RegisterForNavigation<MainPage, MainPageViewModel>();
containerRegistry.RegisterForNavigation<ViewA, ViewAViewModel>();
containerRegistry.RegisterForNavigation<ViewB, ViewBViewModel>();
//依赖注入
//Singleton 单一实例模式:单一实例对象对每个对象和每个请求都是相同的,可以说是不同客户端不同请求都是相同的。
//Transient 暂时性模式:暂时性对象始终不同,无论是不是同一个请求(同一个请求里的不同服务)同一个客户端,每次都是创建新的实例。
//Scoped作用域模式:作用域对象在一个客户端请求中是相同的,但在多个客户端请求中是不同的。
containerRegistry.RegisterSingleton<IExampleAlphaService, ExampleAlphaService>();
containerRegistry.Register<IExampleBetaService, ExampleBetaService>();
}
}
}
页面:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
x:Class="MyXamarin11.Views.MainPage"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="Main Page"
mc:Ignorable="d">
<StackLayout Margin="12" VerticalOptions="Center">
<Button Command="{Binding GoToViewACommand}" Text="导航至页面A" />
<Button Command="{Binding GoToViewBCommand}" Text="导航至页面B" />
</StackLayout>
</ContentPage>
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
x:Class="MyXamarin11.Views.ViewA"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="Page with Singleton Service"
mc:Ignorable="d">
<StackLayout Margin="12" VerticalOptions="Center">
<Label
HorizontalOptions="CenterAndExpand"
HorizontalTextAlignment="Center"
Text="本页面数据使用了RegisterSingleton的依赖注入方式, 返回的随机数将不会变化 "
VerticalOptions="CenterAndExpand" />
<Label
FontSize="Large"
HorizontalOptions="Center"
HorizontalTextAlignment="Center"
Text="{Binding NumberValue}" />
<Button Command="{Binding GoBackCommand}" Text="Go back" />
</StackLayout>
</ContentPage>
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
x:Class="MyXamarin11.Views.ViewB"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Title="{Binding Title}"
mc:Ignorable="d">
<StackLayout Margin="12" VerticalOptions="Center">
<Label
HorizontalOptions="CenterAndExpand"
HorizontalTextAlignment="Center"
Text="本页面数据使用了RegisterTransient的依赖注入方式, 返回的随机数刷新即变化"
VerticalOptions="CenterAndExpand" />
<Label
FontSize="Large"
HorizontalOptions="Center"
HorizontalTextAlignment="Center"
Text="{Binding NumberValue}" />
<Button Command="{Binding GoBackCommand}" Text="Go back" />
</StackLayout>
</ContentPage>
ViewModel:
using System.Collections.Generic;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
namespace MyXamarin11.ViewModels
{
public class ViewModelBase : BindableBase, IInitialize, INavigatedAware
{
protected INavigationService _navigationService { get; }
public ViewModelBase(INavigationService navigationService)
{
_navigationService = navigationService;
Title = GetType().Name.Replace("ViewModel", string.Empty);
GoHomeCommand = new DelegateCommand(OnGoHomeCommandExecuted);
NavigateCommand = new DelegateCommand<string>(OnNavigateCommandExecuted);
}
public string Title { get; }
private IEnumerable<string> _messages;
public IEnumerable<string> Messages
{
get => _messages;
set => SetProperty(ref _messages, value);
}
private int _initializedCount;
public int InitializedCount
{
get => _initializedCount;
set => SetProperty(ref _initializedCount, value, UpdateMessage);
}
private int _onNavigatedFromCount;
public int OnNavigatedFromCount
{
get => _onNavigatedFromCount;
set => SetProperty(ref _onNavigatedFromCount, value, UpdateMessage);
}
private int _onNavigatedToCount;
public int OnNavigatedToCount
{
get => _onNavigatedToCount;
set => SetProperty(ref _onNavigatedToCount, value, UpdateMessage);
}
private void UpdateMessage()
{
Messages = new[]
{
$"Initialized Called: {InitializedCount} time(s)",
$"OnNavigatedFrom Called: {OnNavigatedFromCount} time(s)",
$"OnNavigatedTo Called: {OnNavigatedToCount} time(s)",
};
}
public DelegateCommand GoHomeCommand { get; }
private async void OnGoHomeCommandExecuted()
{
var result = await _navigationService.NavigateAsync("/MainPage");
if(!result.Success)
{
System.Diagnostics.Debugger.Break();
}
}
public DelegateCommand<string> NavigateCommand { get; }
private async void OnNavigateCommandExecuted(string path)
{
var result = await _navigationService.NavigateAsync(path);
if (!result.Success)
{
System.Diagnostics.Debugger.Break();
}
}
public void OnNavigatedFrom(INavigationParameters parameters)
{
OnNavigatedFromCount++;
}
public void OnNavigatedTo(INavigationParameters parameters)
{
OnNavigatedToCount++;
}
public void Initialize(INavigationParameters parameters)
{
InitializedCount++;
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
namespace MyXamarin11.ViewModels
{
public class MainPageViewModel : BindableBase
{
private readonly INavigationService _navigationService;
public DelegateCommand GoToViewACommand { get; private set; }
public DelegateCommand GoToViewBCommand { get; private set; }
//依赖注入
public MainPageViewModel(INavigationService navigationService)
{
_navigationService = navigationService;
GoToViewACommand = new DelegateCommand(GoToViewA);
GoToViewBCommand = new DelegateCommand(GoToViewB);
}
private async void GoToViewB()
{
await _navigationService.NavigateAsync("ViewB");
}
private async void GoToViewA()
{
await _navigationService.NavigateAsync("ViewA"); //ViewA:x:Class="MyXamarin11.Views.ViewA"
}
}
}
using MyXamarin11.Services;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
namespace MyXamarin11.ViewModels
{
public class ViewAViewModel : BindableBase
{
private readonly INavigationService _navigationService;
private int _numberValue;
public int NumberValue
{
get => _numberValue;
set => SetProperty(ref _numberValue, value);
}
public DelegateCommand GoBackCommand { get; private set; }
public ViewAViewModel(INavigationService navigationService,IExampleAlphaService exampleAlphaService)
{
_navigationService = navigationService;
NumberValue = exampleAlphaService.NumberValue; //随机生成数据
GoBackCommand = new DelegateCommand(GoBack);
}
private async void GoBack()
{
await _navigationService.GoBackAsync();
}
}
}
using MyXamarin11.Services;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
namespace MyXamarin11.ViewModels
{
public class ViewBViewModel : BindableBase
{
private readonly INavigationService _navigationService;
private int _numberValue;
public int NumberValue
{
get => _numberValue;
set => SetProperty(ref _numberValue, value);
}
public DelegateCommand GoBackCommand { get; private set; }
public ViewBViewModel(INavigationService navigationService,
IExampleBetaService exampleBetaService)
{
_navigationService = navigationService;
NumberValue = exampleBetaService.NumberValue;
GoBackCommand = new DelegateCommand(GoBack);
}
private async void GoBack()
{
await _navigationService.GoBackAsync();
}
}
}
效果:
源码:https://download.csdn.net/download/helldoger/85525789