WPF Prism.Core version 9.0.537 implemented navigation register singleton with splash screen, pass global variable via RegisterSingleton method

Install-Package Prism.Core -v 9.0.537
Install-Package Prism.Wpf -v 9.0.537
Install-Package Prism.DryIoc -v 9.0.537

 

 

<prism:PrismApplication x:Class="WpfApp29.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:prism="http://prismlibrary.com/"
             ShutdownMode="OnExplicitShutdown">
    <prism:PrismApplication.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="FontSize" Value="30"/>
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
        </Style>
        <Style TargetType="TextBox">
            <Setter Property="FontSize" Value="30"/>
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
            <Setter Property="VerticalAlignment" Value="Stretch"/>
        </Style>
    </prism:PrismApplication.Resources>
</prism:PrismApplication>

using Prism.DryIoc;
using Prism.Ioc;
using System.Windows;
using WpfApp29.ViewModels;
using WpfApp29.Views;

namespace WpfApp29
{
    public partial class App : PrismApplication
    {
        public App()
        {
            Application.Current.Dispatcher.UnhandledException += Dispatcher_UnhandledException;
            Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            var splash = new SplashWin();
            splash.ShowDialog();
            base.OnStartup(e);
        }

        private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            string exMsg = $"{DateTime.Now},{e.Exception.StackTrace}";
            MessageBox.Show(exMsg);
            e.Handled = true;
        }

        private void Dispatcher_UnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            string exMsg = $"{DateTime.Now},{e.Exception.StackTrace}";
            MessageBox.Show(exMsg);
            e.Handled = true;
        }

        protected override Window CreateShell()
        {
            return new MainWin();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterSingleton<BooksViewModel>();
            //containerRegistry.RegisterForNavigation<MainWin,MainWinViewModel>();
            containerRegistry.RegisterForNavigation<Books, BooksViewModel>("Books");            
            containerRegistry.RegisterForNavigation<AddBook, AddBookViewModel>("AddBook");
            containerRegistry.RegisterForNavigation<EditBooks, EditBooksViewModel>("EditBook");
        }

        protected override void ConfigureRegionAdapterMappings(RegionAdapterMappings regionAdapterMappings)
        {
            base.ConfigureRegionAdapterMappings(regionAdapterMappings);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;

namespace WpfApp29.ViewModels
{
    public class MainWinViewModel : BindableBase
    {
        private IRegionManager regionManager;
        private BooksViewModel booksVM;
        public DelegateCommand ViewBooksCommand => new DelegateCommand(ViewBooksCommandExecuted);
        public DelegateCommand AddBookCommand => new DelegateCommand(AddBookCommandExecuted);
        public DelegateCommand EditBookCommand => new DelegateCommand(EditBookCommandExecuted);

        private void AddBookCommandExecuted()
        {
            Navigate("AddBook");
        }

        private void EditBookCommandExecuted()
        {
            if(booksVM.SelectedBk==null)
            {
                MessageBox.Show("No book selected");
                return;
            }
            Navigate("EditBook");
        }

        private void ViewBooksCommandExecuted()
        {
            Navigate("Books");
        }

        public MainWinViewModel(IRegionManager regionManagerValue,BooksViewModel bookVMValue)
        {
            regionManager = regionManagerValue;
            booksVM = bookVMValue;
            NavigateOnLoaded();
        }

        private async void NavigateOnLoaded()
        {
            await Task.Delay(1);
            Navigate("Books");
        }

        private void Navigate(string viewName)
        {
            regionManager.RequestNavigate("ContentRegion", viewName);
        }
    }
}

 

//D:\C\WpfApp29\WpfApp29\App.xaml
<prism:PrismApplication x:Class="WpfApp29.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:prism="http://prismlibrary.com/"
             ShutdownMode="OnExplicitShutdown">
    <prism:PrismApplication.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="FontSize" Value="30"/>
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
        </Style>
        <Style TargetType="TextBox">
            <Setter Property="FontSize" Value="30"/>
            <Setter Property="HorizontalAlignment" Value="Stretch"/>
            <Setter Property="VerticalAlignment" Value="Stretch"/>
        </Style>
    </prism:PrismApplication.Resources>
</prism:PrismApplication>

//D:\C\WpfApp29\WpfApp29\App.xaml.cs
using Prism.DryIoc;
using Prism.Ioc;
using System.Windows;
using WpfApp29.ViewModels;
using WpfApp29.Views;

namespace WpfApp29
{
    public partial class App : PrismApplication
    {
        public App()
        {
            Application.Current.Dispatcher.UnhandledException += Dispatcher_UnhandledException;
            Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;
        }

        protected override void OnStartup(StartupEventArgs e)
        {
            var splash = new SplashWin();
            splash.ShowDialog();
            base.OnStartup(e);
        }

        private void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            string exMsg = $"{DateTime.Now},{e.Exception.StackTrace}";
            MessageBox.Show(exMsg);
            e.Handled = true;
        }

        private void Dispatcher_UnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            string exMsg = $"{DateTime.Now},{e.Exception.StackTrace}";
            MessageBox.Show(exMsg);
            e.Handled = true;
        }

        protected override Window CreateShell()
        {
            return new MainWin();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterSingleton<BooksViewModel>();
            //containerRegistry.RegisterForNavigation<MainWin,MainWinViewModel>();
            containerRegistry.RegisterForNavigation<Books, BooksViewModel>("Books");            
            containerRegistry.RegisterForNavigation<AddBook, AddBookViewModel>("AddBook");
            containerRegistry.RegisterForNavigation<EditBooks, EditBooksViewModel>("EditBook");
        }

        protected override void ConfigureRegionAdapterMappings(RegionAdapterMappings regionAdapterMappings)
        {
            base.ConfigureRegionAdapterMappings(regionAdapterMappings);
        }
    }
}

//D:\C\WpfApp29\WpfApp29\Views\SplashWin.xaml
<Window x:Class="WpfApp29.Views.SplashWin"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp29.Views"
        mc:Ignorable="d"
        Title="SplashWin" WindowState="Maximized">
    <Grid>
        <Grid 
                MouseDown="Button_Click">
            <Grid.Background>
                <ImageBrush ImageSource="pack://application:,,,/WpfApp29;component/Resources/Images/333.jpg" />
            </Grid.Background>
        </Grid>
    </Grid>
</Window>

//D:\C\WpfApp29\WpfApp29\Views\SplashWin.xaml.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfApp29.Views
{
    /// <summary>
    /// Interaction logic for SplashWin.xaml
    /// </summary>
    public partial class SplashWin : Window
    {
        public SplashWin()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //DialogResult = true;
            this.Close();
        }
    }
}

//D:\C\WpfApp29\WpfApp29\Views\MainWin.xaml <Window x:Class="WpfApp29.Views.MainWin" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp29.Views" xmlns:prism="http://prismlibrary.com/" prism:ViewModelLocator.AutoWireViewModel="True" mc:Ignorable="d" Title="MainWin" WindowState="Maximized"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <StackPanel Grid.Row="0" Orientation="Horizontal" Margin="10" HorizontalAlignment="Left"> <Button Content="BooksView" Command="{Binding ViewBooksCommand}" Margin="5"/> <Button Content="Add Book" Command="{Binding AddBookCommand}" Margin="5"/> <Button Content="Edit Book" Command="{Binding EditBookCommand}" Margin="5"/> </StackPanel> <ContentControl Grid.Row="1" prism:RegionManager.RegionName="ContentRegion" Margin="10"/> </Grid> </Window> //D:\C\WpfApp29\WpfApp29\ViewModels\MainWinViewModel.cs using System; using System.Collections.Generic; using System.Text; using System.Windows; namespace WpfApp29.ViewModels { public class MainWinViewModel : BindableBase { private IRegionManager regionManager; private BooksViewModel booksVM; public DelegateCommand ViewBooksCommand => new DelegateCommand(ViewBooksCommandExecuted); public DelegateCommand AddBookCommand => new DelegateCommand(AddBookCommandExecuted); public DelegateCommand EditBookCommand => new DelegateCommand(EditBookCommandExecuted); private void AddBookCommandExecuted() { Navigate("AddBook"); } private void EditBookCommandExecuted() { if(booksVM.SelectedBk==null) { MessageBox.Show("No book selected"); return; } Navigate("EditBook"); } private void ViewBooksCommandExecuted() { Navigate("Books"); } public MainWinViewModel(IRegionManager regionManagerValue,BooksViewModel bookVMValue) { regionManager = regionManagerValue; booksVM = bookVMValue; NavigateOnLoaded(); } private async void NavigateOnLoaded() { await Task.Delay(1); Navigate("Books"); } private void Navigate(string viewName) { regionManager.RequestNavigate("ContentRegion", viewName); } } } //D:\C\WpfApp29\WpfApp29\Views\AddBooks.xaml <UserControl x:Class="WpfApp29.Views.AddBook" 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:WpfApp29.Views" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"> <Grid> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <TextBlock Grid.Row="0" Grid.Column="0" Text="Id:"/> <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding NewBook.Id}"/> <TextBlock Grid.Row="1" Grid.Column="0" Text="Name:"/> <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding NewBook.Name}"/> <TextBlock Grid.Row="2" Grid.Column="0" Text="ISBN:"/> <TextBox Grid.Row="2" Grid.Column="1" Text="{Binding NewBook.ISBN}"/> <Button Grid.Row="3" Grid.Column="0" Content="Cancel" Command="{Binding CancelCommand}"/> <Button Grid.Row="3" Grid.Column="1" Content="Save" Command="{Binding SaveCommand}"/> </Grid> </UserControl> //D:\C\WpfApp29\WpfApp29\ViewModels\AddBookViewModel.cs using System; using System.Collections.Generic; using System.Text; using WpfApp29.Models; namespace WpfApp29.ViewModels { public class AddBookViewModel : BindableBase,INavigationAware { private BooksViewModel booksVM; public DelegateCommand CancelCommand => new DelegateCommand(CancelCommandExecuted); public DelegateCommand SaveCommand => new DelegateCommand(SaveCommandExecuted); public AddBookViewModel(BooksViewModel booksVMValue) { booksVM = booksVMValue; InitNewBook(); } private void CancelCommandExecuted() { return; } private void SaveCommandExecuted() { if (NewBook != null && NewBook.Id > 0) { booksVM.BooksCollection.Add(NewBook); } InitNewBook(); } public void OnNavigatedTo(NavigationContext navigationContext) { InitNewBook(); } private void InitNewBook() { NewBook = new Book(); var lastBk = booksVM.BooksCollection.LastOrDefault(); NewBook.Id = lastBk != null ? lastBk.Id + 1 : 1; } public bool IsNavigationTarget(NavigationContext navigationContext) { return true; } public void OnNavigatedFrom(NavigationContext navigationContext) { } private Book newBook; public Book NewBook { get { return newBook; } set { SetProperty(ref newBook, value); } } } } //D:\C\WpfApp29\WpfApp29\Views\Books.xaml <UserControl x:Class="WpfApp29.Views.Books" 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:WpfApp29.Views" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"> <Grid> <DataGrid ItemsSource="{Binding BooksCollection}" VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" VirtualizingPanel.CacheLength="2,2" VirtualizingPanel.CacheLengthUnit="Item" EnableColumnVirtualization="True" EnableRowVirtualization="True" ScrollViewer.CanContentScroll="True" ScrollViewer.IsDeferredScrollingEnabled="True" SnapsToDevicePixels="True" UseLayoutRounding="True" AutoGenerateColumns="True" CanUserAddRows="False" IsReadOnly="True" SelectionMode="Single" SelectedItem="{Binding SelectedBk,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"> <DataGrid.Resources> <Style TargetType="DataGridRow"> <Setter Property="FontSize" Value="30"/> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="FontSize" Value="50"/> <Setter Property="Foreground" Value="Red"/> </Trigger> </Style.Triggers> </Style> </DataGrid.Resources> </DataGrid> </Grid> </UserControl> //D:\C\WpfApp29\WpfApp29\ViewModels\BooksViewModel.cs using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Dynamic; using System.Printing; using System.Text; using WpfApp29.Models; namespace WpfApp29.ViewModels { public class BooksViewModel : BindableBase { private static long idx = 0; private static readonly object objLock = new object(); private static long GetIdx() { return Interlocked.Increment(ref idx); } public BooksViewModel() { InitBooksCollection(); } private void InitBooksCollection() { BooksCollection = new ObservableCollection<Book>(); for (int i = 0; i < 100; i++) { var a = GetIdx(); BooksCollection.Add(new Book() { Id = a, Name = $"Name_{a}", ISBN = $"ISBN_{a}_{Guid.NewGuid():N}" }); } } private ObservableCollection<Book> booksCollection; public ObservableCollection<Book> BooksCollection { get { return booksCollection; } set { SetProperty(ref booksCollection, value); } } private Book selectedBk; public Book SelectedBk { get { return selectedBk; } set { SetProperty(ref selectedBk, value); } } } } //D:\C\WpfApp29\WpfApp29\Views\EditBooks.xaml <UserControl x:Class="WpfApp29.Views.EditBooks" 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:WpfApp29.Views" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"> <Grid> <Grid.RowDefinitions> <RowDefinition/> <RowDefinition/> <RowDefinition/> <RowDefinition/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition/> <ColumnDefinition/> </Grid.ColumnDefinitions> <TextBlock Grid.Row="0" Grid.Column="0" Text="Id:"/> <TextBlock Grid.Row="0" Grid.Column="1" Text="{Binding SelectedBook.Id, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/> <TextBlock Grid.Row="1" Grid.Column="0" Text="Name:"/> <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding SelectedBook.Name, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/> <TextBlock Grid.Row="2" Grid.Column="0" Text="ISBN:"/> <TextBox Grid.Row="2" Grid.Column="1" Text="{Binding SelectedBook.ISBN, Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/> <Button Grid.Row="3" Grid.Column="0" Content="Cancel" Command="{Binding CancelCommand}"/> <Button Grid.Row="3" Grid.Column="1" Content="Update" Command="{Binding UpdateCommand}"/> </Grid> </UserControl> //D:\C\WpfApp29\WpfApp29\ViewModels\EditBooksViewModel.cs using System; using System.Collections.Generic; using System.Text; using System.Windows; using WpfApp29.Models; namespace WpfApp29.ViewModels { public class EditBooksViewModel : BindableBase, INavigationAware { public DelegateCommand CancelCommand { get; set; } public DelegateCommand UpdateCommand { get; set; } private BooksViewModel booksVM; public EditBooksViewModel(BooksViewModel booksVMValue) { CancelCommand = new DelegateCommand(CancelCommandExecuted); UpdateCommand = new DelegateCommand(UpdateCommandExecuted); booksVM= booksVMValue; SelectedBook = booksVM.SelectedBk; } private void UpdateCommandExecuted() { int selectedIdx = booksVM.BooksCollection.IndexOf(SelectedBook); if(selectedIdx>=0) { booksVM.BooksCollection.RemoveAt(selectedIdx); booksVM.BooksCollection.Insert(selectedIdx, SelectedBook); MessageBox.Show($"{DateTime.Now},update BookId:{SelectedBook.Id} successfully"); } } private void CancelCommandExecuted() { return; } public void OnNavigatedTo(NavigationContext navigationContext) { SelectedBook = booksVM.SelectedBk; } public bool IsNavigationTarget(NavigationContext navigationContext) { return true; } public void OnNavigatedFrom(NavigationContext navigationContext) { } private Book selectedBook; public Book SelectedBook { get { return selectedBook; } set { SetProperty(ref selectedBook, value); } } } }

 

 

image

 

 

 

 

 

 

 

 

image

 

 

image

 

 

image

 

 

 

 

 

image

 

 

 

 

 

 

image

 

 

 

 

 

 

 

image

 

posted @ 2026-05-13 21:31  FredGrit  阅读(14)  评论(0)    收藏  举报