WPF Prism.WPF, IModule,IRegionManager,IEventAggregator to navigate module to region part, communication cross project via pubsubevent from IEventAggregator

Install-Package Prism.Unity;
Install-Package Prism.WPF; 

 

//IEventAggregator
using System;
using System.Collections.Generic;
using System.Text;

namespace Framework.Common.Models
{
    public class MsgPayload
    {
        public string TimeStr { get; set; }
        public string Msg { get; set; }
    }

    public class PubSubMsgEvent : PubSubEvent<MsgPayload>
    {
    }
}


private async Task PopulateBooksCollectionAsync(List<Book> booksList)
{
    await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
    {
        var tempList = booksList.ToList();
        booksList.Clear();
        foreach (var bk in tempList)
        {
            BooksCollection.Add(bk);
        }
    }, System.Windows.Threading.DispatcherPriority.Background);
    MsgPayload msgPayload = new MsgPayload()
    {
        TimeStr = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")}",
        Msg = $"Loaded {BooksCollection.Count} items"
    };
    eventAggregator.GetEvent<PubSubMsgEvent>().Publish(msgPayload);
}

IEventAggregator eventAggregator;
public MainVM(IEventAggregator eventAggregatorValue)
{
    eventAggregator = eventAggregatorValue;
    eventAggregator.GetEvent<PubSubMsgEvent>().Subscribe(OnPubSubReceived);
}

private void OnPubSubReceived(MsgPayload payload)
{
    StatusMsg = $"{payload.TimeStr},{payload.Msg}";
}

 

 

//IModule
using BookProject.Services;
using BookProject.ViewModels;
using BookProject.Views;
using System;
using System.Collections.Generic;
using System.Text;

namespace BookProject
{
    public class BookModule : IModule
    {
        public void OnInitialized(IContainerProvider containerProvider)
        {
            containerProvider.GetContainer().Resolve<BookView>();
        }

        public void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.Register<IIDService, IDService>();
            containerRegistry.Register<INameService, NameService>();
            containerRegistry.Register<IISBNService, ISBNService>();
            containerRegistry.RegisterForNavigation<BookView, BookViewModel>("BookView");
        }
    }
}




using ImageProject.ViewModel;
using ImageProject.Views;
using System;
using System.Collections.Generic;
using System.Text;

namespace ImageProject
{
    public class ImageModule : IModule
    {
        public void OnInitialized(IContainerProvider containerProvider)
        {
            containerProvider.GetContainer().Resolve<ImageView>();
        }

        public void RegisterTypes(IContainerRegistry containerRegistry)
        {

             containerRegistry.RegisterForNavigation<ImageView, ImageViewModel>("ImageView");
        }
    }
}

//App.xaml.cs
using BookProject;
using ImageProject;
using Microsoft.Extensions.DependencyInjection;
using System.Configuration;
using System.Data;
using System.Windows; 
using WpfApp32.ViewModels;

namespace WpfApp32
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : PrismApplication
    {
        IServiceProvider serviceProvider;
        IRegionManager regionManager;
        protected override Window CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterForNavigation<MainWindow, MainVM>();            
        }


        protected override void OnInitialized()
        {
            base.OnInitialized();
            regionManager = Container.Resolve<IRegionManager>();
            regionManager.RequestNavigate("LeftRegion", "BookView");
            regionManager.RequestNavigate("RightRegion", "ImageView");
        }


        protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
        {
            base.ConfigureModuleCatalog(moduleCatalog);
            moduleCatalog.AddModule<BookModule>();
            moduleCatalog.AddModule<ImageModule>();
        }
    }

}

 

 

 

image

 

 

image

 

 

 

image

 

 

 

 

 

image

 

 

//Framework project
using System;
using System.Collections.Generic;
using System.Text;

namespace Framework.Common.Models
{
    public class MsgPayload
    {
        public string TimeStr { get; set; }
        public string Msg { get; set; }
    }

    public class PubSubMsgEvent : PubSubEvent<MsgPayload>
    {
    }
}


using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;

namespace Framework.Common.Utils
{
    public static  class CommonUtility
    {
        public static string GetMemory()
        {
            var memory = Process.GetCurrentProcess().PrivateMemorySize64 / 1024.0d / 1024.0d;
            return $"Memory:{memory:F2} M";
        }
    }
}


//BookProject
using System;
using System.Collections.Generic;
using System.Text;

namespace BookProject.Models
{
    public class Book
    {
        public int Id { get; set; }
        public string ISBN { get; set; }
        public string Name { get; set; }
        public string Title { get; set; }
        public string Topic { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Text;

namespace BookProject.Services
{
    public interface IIDService
    {
        int GetID();
    }

    public class IDService : IIDService
    {
        int idx = 0;
        public int GetID()
        {
            return Interlocked.Increment(ref idx);
        }
    }

    public interface INameService
    {
        string GetName();
    }

    public class NameService : INameService
    {
        int idx = 0;
        public string GetName()
        {
            return $"Name_{Interlocked.Increment(ref idx)}";
        }
    }

    public interface IISBNService
    {
        string GetISBN();
    }

    public class ISBNService : IISBNService
    {
        int idx = 0;
        public string GetISBN()
        {
            return $"ISBN_{Interlocked.Increment(ref idx)}+{Guid.NewGuid():N}";
        }
    }
}

using BookProject.Models;
using BookProject.Services;
using Framework.Common.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows.Data;

namespace BookProject.ViewModels
{
    public class BookViewModel : BindableBase
    {
        IEventAggregator eventAggregator;
        IIDService idService;
        INameService nameService;
        IISBNService isbnService;
        public BookViewModel(IEventAggregator eventAggregatorValue, IIDService idServiceValue,
            INameService nameServiceValue, IISBNService isbnServiceValue)
        {
            eventAggregator = eventAggregatorValue;
            idService = idServiceValue;
            nameService = nameServiceValue;
            isbnService = isbnServiceValue;
            InitializeBooksCollection();
        }

        public async Task InitializeBooksCollection()
        {
            BooksCollection=new ObservableCollection<Book>();
            List<Book> booksList=new List<Book>();
            for(int i = 1; i < 10001001; i++)
            {
                booksList.Add(new Book()
                {
                    Id = idService.GetID(),
                    Name = nameService.GetName(),
                    ISBN = isbnService.GetISBN(),
                    Title = $"Title_{i}",
                    Topic = $"Topic_{i}"
                });

                if(i%100000==0)
                {
                    await PopulateBooksCollectionAsync(booksList);
                }
            }

            if(booksList.Any())
            {
                await PopulateBooksCollectionAsync(booksList);
            }

            MsgPayload msgPayload = new MsgPayload()
            {
                TimeStr = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")}",
                Msg = $"Loaded {BooksCollection.Count} items completely"
            };
            eventAggregator.GetEvent<PubSubMsgEvent>().Publish(msgPayload);
        }

        private async Task PopulateBooksCollectionAsync(List<Book> booksList)
        {
            await System.Windows.Application.Current.Dispatcher.InvokeAsync(() =>
            {
                var tempList = booksList.ToList();
                booksList.Clear();
                foreach (var bk in tempList)
                {
                    BooksCollection.Add(bk);
                }
            }, System.Windows.Threading.DispatcherPriority.Background);
            MsgPayload msgPayload = new MsgPayload()
            {
                TimeStr = $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")}",
                Msg = $"Loaded {BooksCollection.Count} items"
            };
            eventAggregator.GetEvent<PubSubMsgEvent>().Publish(msgPayload);
        }

        private ObservableCollection<Book> booksCollction;
        public ObservableCollection<Book> BooksCollection
        {
            get
            {
                return booksCollction;
            }
            set
            {
                SetProperty(ref booksCollction, value);
            }
        }

    }
}


<UserControl x:Class="BookProject.Views.BookView"
             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:BookProject.Views"
             xmlns:prism="http://prismlibrary.com/"
             prism:ViewModelLocator.AutoWireViewModel="True"
             VerticalAlignment="Stretch"
             HorizontalAlignment="Stretch"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <DataGrid ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                      VirtualizingPanel.IsVirtualizing="True"
                      VirtualizingPanel.VirtualizationMode="Recycling"
                      VirtualizingPanel.CacheLengthUnit="Item"
                      VirtualizingPanel.CacheLength="2,2"
                      ScrollViewer.IsDeferredScrollingEnabled="True"
                      ScrollViewer.CanContentScroll="True"
                      FontSize="20"
                      AutoGenerateColumns="True"
                      CanUserAddRows="False">
        </DataGrid>
    </Grid>
</UserControl>
using BookProject.Services;
using BookProject.ViewModels;
using BookProject.Views;
using System;
using System.Collections.Generic;
using System.Text;

namespace BookProject
{
    public class BookModule : IModule
    {
        public void OnInitialized(IContainerProvider containerProvider)
        {
            containerProvider.GetContainer().Resolve<BookView>();
        }

        public void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.Register<IIDService, IDService>();
            containerRegistry.Register<INameService, NameService>();
            containerRegistry.Register<IISBNService, ISBNService>();
            containerRegistry.RegisterForNavigation<BookView, BookViewModel>("BookView");
        }
    }
}


//ImageProject
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;

namespace ImageProject.ViewModel
{
    public class ImageViewModel : BindableBase
    {
        ConcurrentDictionary<string, ImageSource> imgCacheDic = new ConcurrentDictionary<string, ImageSource>();
        public ImageViewModel()
        {
            InitImgsCollection();
        }

        private void InitImgsCollection()
        {
            ImgsCollection = new ObservableCollection<ImageSource>();
            var imgs = Directory.GetFiles(@"Images");
            if (imgs == null || !imgs.Any())
            {
                return;
            }

            int imgsCount = imgs.Count();
            for (int i = 1; i < 1000101; i++)
            {
                ImgsCollection.Add(GetImgSourceViaUrl(imgs[i%imgsCount]));
            }
        }

        private ImageSource GetImgSourceViaUrl(string imgUrl)
        {
            if (!File.Exists(imgUrl))
            {
                return null;
            }

            if(imgCacheDic.TryGetValue(imgUrl, out ImageSource imgSource))
            {
                return imgSource;
            }

            BitmapImage bmi = new BitmapImage();
            bmi.BeginInit();
            bmi.UriSource = new Uri(imgUrl, UriKind.RelativeOrAbsolute);
            bmi.EndInit();
            if(bmi.CanFreeze)
            {
                bmi.Freeze();
            }
            imgCacheDic[imgUrl] = bmi;
            return bmi;
        }

        private ObservableCollection<ImageSource> imgsCollection;
        public ObservableCollection<ImageSource> ImgsCollection
        {
            get
            {
                return imgsCollection;
            }
            set
            {
                SetProperty(ref imgsCollection, value);
            }
        }
    }
}
<UserControl x:Class="ImageProject.Views.ImageView"
             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:ImageProject.Views"
             xmlns:prism="http://prismlibrary.com/"
             prism:ViewModelLocator.AutoWireViewModel="True"
             VerticalAlignment="Stretch"
             HorizontalAlignment="Stretch"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <ListBox ItemsSource="{Binding ImgsCollection}"
                     VirtualizingPanel.IsVirtualizing="True"
                     VirtualizingPanel.VirtualizationMode="Recycling"
                     VirtualizingPanel.CacheLength="2,2"
                     VirtualizingPanel.CacheLengthUnit="Item"
                     ScrollViewer.IsDeferredScrollingEnabled="True"
                     >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Image Source="{Binding}"  Stretch="UniformToFill"
                           Width="{Binding DataContext.ImageWidth,RelativeSource={RelativeSource AncestorType=Window}}"
                           Height="{Binding DataContext.ImageHeight,RelativeSource={RelativeSource AncestorType=Window}}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</UserControl>
using ImageProject.ViewModel;
using ImageProject.Views;
using System;
using System.Collections.Generic;
using System.Text;

namespace ImageProject
{
    public class ImageModule : IModule
    {
        public void OnInitialized(IContainerProvider containerProvider)
        {
            containerProvider.GetContainer().Resolve<ImageView>();
        }

        public void RegisterTypes(IContainerRegistry containerRegistry)
        {

             containerRegistry.RegisterForNavigation<ImageView, ImageViewModel>("ImageView");
        }
    }
}

//MainWindow
<prism:PrismApplication x:Class="WpfApp32.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp32"
             xmlns:prism="http://prismlibrary.com/">
    <prism:PrismApplication.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="FontSize" Value="30"/>
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                    <Setter Property="Foreground" Value="Red"/>
                    <Setter Property="FontSize" Value="40"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </prism:PrismApplication.Resources>
</prism:PrismApplication>

using BookProject;
using ImageProject;
using Microsoft.Extensions.DependencyInjection;
using System.Configuration;
using System.Data;
using System.Windows; 
using WpfApp32.ViewModels;

namespace WpfApp32
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : PrismApplication
    {
        IServiceProvider serviceProvider;
        IRegionManager regionManager;
        protected override Window CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterForNavigation<MainWindow, MainVM>();            
        }


        protected override void OnInitialized()
        {
            base.OnInitialized();
            regionManager = Container.Resolve<IRegionManager>();
            regionManager.RequestNavigate("LeftRegion", "BookView");
            regionManager.RequestNavigate("RightRegion", "ImageView");
        }


        protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
        {
            base.ConfigureModuleCatalog(moduleCatalog);
            moduleCatalog.AddModule<BookModule>();
            moduleCatalog.AddModule<ImageModule>();
        }
    }

}<Window x:Class="WpfApp32.MainWindow"
        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:prism="http://prismlibrary.com/"
        xmlns:local="clr-namespace:WpfApp32"
        mc:Ignorable="d"
        WindowState="Maximized"
        Title="{Binding MainTitle}" Height="450" Width="800">
    <Window.Resources>
       
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <TextBlock Text="{Binding TitleStr}" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2"/>
        <ContentControl Grid.Row="1" Grid.Column="0"
                        prism:RegionManager.RegionName="LeftRegion"/>
        <ContentControl Grid.Row="1" Grid.Column="1"
                        prism:RegionManager.RegionName="RightRegion"/>
        <TextBlock Grid.Row="2" Text="{Binding StatusMsg}" Grid.Column="0" Grid.ColumnSpan="2"/>
    </Grid>
</Window>
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.Navigation;
using System.Windows.Shapes;
using WpfApp32.ViewModels;

namespace WpfApp32
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow(MainVM vm)
        {
            InitializeComponent();
            this.DataContext = vm;
            this.Loaded += async (s, e) =>
            {
                vm.ImageWidth = this.ActualWidth / 2;
                vm.ImageHeight = this.ActualHeight;
            };
        }
    }
}using Framework.Common.Models;
using Framework.Common.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;

namespace WpfApp32.ViewModels
{
    public class MainVM : BindableBase
    {
        int idx = 0;
        IEventAggregator eventAggregator;
        public MainVM(IEventAggregator eventAggregatorValue)
        {
            eventAggregator = eventAggregatorValue;
            eventAggregator.GetEvent<PubSubMsgEvent>().Subscribe(OnPubSubReceived);
            MainTitle = $"{Interlocked.Increment(ref idx)}_{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")}";
            TitleStr = $"{idx}_{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")},{CommonUtility.GetMemory()}";
            Task.Run(() =>
            {
                InitTimer();
            });
        }

        private void OnPubSubReceived(MsgPayload payload)
        {
            StatusMsg = $"{payload.TimeStr},{payload.Msg}";
        }

        private void InitTimer()
        {
            System.Timers.Timer tmr = new System.Timers.Timer();
            tmr.Interval = 1000;
            tmr.Elapsed += Tmr_Elapsed;
            tmr.Start();
        }

        private void Tmr_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
        {
            MainTitle = $"{Interlocked.Increment(ref idx)}_{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")}";
            TitleStr = $"{idx}_{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")},{CommonUtility.GetMemory()}";
        }

       

        private string mainTitle;
        public string MainTitle
        {
            get
            {
                return mainTitle;
            }
            set
            {
                SetProperty(ref mainTitle, value);
            }
        }

        private string titleStr;
        public string TitleStr
        {
            get
            {
                return titleStr;
            }
            set
            {
                SetProperty(ref titleStr, value);
            }
        }

        private string statusMsg;
        public string StatusMsg
        {
            get
            {
                return statusMsg;
            }
            set
            {
                SetProperty(ref statusMsg, value);
            }
        }

        private double imageWidth;
        public double ImageWidth
        {
            get
            {
                return imageWidth;
            }
            set
            {
                SetProperty(ref imageWidth, value);
            }
        }

        private double imageHeight;
        public double ImageHeight
        {
            get
            {
                return imageHeight;
            }
            set
            {
                SetProperty(ref imageHeight, value);
            }
        }
    }
}

 

posted @ 2025-10-14 21:10  FredGrit  阅读(5)  评论(0)    收藏  举报