WPF Prism IEventAggregator GetEvent<T>().Publish IEventAggregator.GetEvent<T>().Subscribe

Install-Package Prism.Wpf;
Install-Package Prism.Unity;

 

 

 

public class ViewBViewModel:BindableBase
{
    ITimeService timeService;
    IGuidService guidService;
    private readonly IEventAggregator eventAggregator;

    public ViewBViewModel(ITimeService timeServiceValue,IGuidService guidServiceValue, 
        IEventAggregator eventAggregatorValue)
    {
        timeService = timeServiceValue;
        guidService = guidServiceValue;
        eventAggregator = eventAggregatorValue;
        SendBookPayloadCommand = new DelegateCommand(SendBookPayloadCommandExecuted);
    }

    private void SendBookPayloadCommandExecuted()
    {
        var bk = new BookPayload()
        {
            Time = timeService.GetTimeNow(),
            ISBN = guidService.GetGuid()
        };

        //Get the event and publish it with the payload
        eventAggregator.GetEvent<BookChangedEvent>().Publish(bk);
    }
}


public class ViewAViewModel:BindableBase
{
    private readonly IEventAggregator eventAggregator;
    public ViewAViewModel(IEventAggregator eventAggregatorValue)
    {
        eventAggregator=eventAggregatorValue;
        eventAggregator.GetEvent<BookChangedEvent>().Subscribe(OnBookChanged,
            ThreadOption.PublisherThread,
            false);
        SetSize();
        BooksCollection = new ObservableCollection<BookPayload>();
    }

    private void OnBookChanged(BookPayload payload)
    {
        BooksCollection.Add(payload);
    }
}

 

image

 

 

 

image

 

 

 

image

 

 

 

//App.xaml
<prism:PrismApplication x:Class="WpfApp21.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:WpfApp21"
             xmlns:prism="http://prismlibrary.com/">
    <prism:PrismApplication.Resources>
        
    </prism:PrismApplication.Resources>
</prism:PrismApplication>


//App.xaml.cs
using System.Configuration;
using System.Data;
using System.Windows;
using WpfApp21.Services;
using WpfApp21.ViewModels;
using WpfApp21.Views;

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

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.Register<ITimeService, TimeService>();
            containerRegistry.Register<IGuidService, GuidService>();
            containerRegistry.RegisterForNavigation<ViewA, ViewAViewModel>("ViewA");
            containerRegistry.RegisterForNavigation<ViewB, ViewBViewModel>("ViewB");
            containerRegistry.RegisterForNavigation<MainWindow, MainWindowViewModel>("MainWin");
        }

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

}


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

namespace WpfApp21.Services
{
    public interface ITimeService
    {
        string GetTimeNow();
    }

    public class TimeService : ITimeService
    {
        int idx = 0;
        public string GetTimeNow()
        {
            return $"Id:{Interlocked.Increment(ref idx)}_{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}";
        }
    }

    public interface IGuidService
    {
        string GetGuid();
    }

    public class GuidService : IGuidService
    {
        int idx = 0;
        public string GetGuid()
        {
            return $"Guid_{Interlocked.Increment(ref idx)}_{Guid.NewGuid():N}";
        }
    }
}


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

namespace WpfApp21
{
    public class BookPayload
    {
        public string Time { get;set; }
        public string ISBN { get; set; }
    }

    public class BookChangedEvent:PubSubEvent<BookPayload>
    {

    }
}


//MainView.xaml
<Window x:Class="WpfApp21.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:local="clr-namespace:WpfApp21"
        mc:Ignorable="d"
        WindowState="Maximized"
        Title="{Binding MainTitle}" Height="450" Width="800"
        xmlns:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="True">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="3*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <TextBlock Text="Main Window" FontSize="100" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2"/>
        <ContentControl prism:RegionManager.RegionName="LeftRegion"
                        Grid.Row="1"
                        Grid.Column="0"
                        VerticalAlignment="Stretch"
                        HorizontalAlignment="Stretch"/>
        <ContentControl prism:RegionManager.RegionName="RightRegion"
                        Grid.Row="1"
                        Grid.Column="1"
                        VerticalAlignment="Stretch"
                        HorizontalAlignment="Stretch"/>
    </Grid>
</Window>


//MainWindowViewModel.cs
using System;
using System.Collections.Generic;
using System.Text;

namespace WpfApp21.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        public MainWindowViewModel()
        {
            MainTitle = $"In Main Window,now is {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}";
            System.Timers.Timer tmr=new System.Timers.Timer();
            tmr.Elapsed += Tmr_Elapsed;
            tmr.Interval = 1000;
            tmr.Start();
        }

        private void Tmr_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
        {
            MainTitle = $"In Main Window,now is {DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}";
        }

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



//ViewA.xaml
<UserControl x:Class="WpfApp21.Views.ViewA"
             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:WpfApp21.Views"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800"
             xmlns:prism="http://prismlibrary.com/"
             prism:ViewModelLocator.AutoWireViewModel="True"
             VerticalAlignment="Stretch"
             HorizontalAlignment="Stretch">
    <Grid>
        <ListBox ItemsSource="{Binding BooksCollection,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                 VirtualizingPanel.IsVirtualizing="True"
                 VirtualizingPanel.CacheLengthUnit="Item"
                 VirtualizingPanel.CacheLength="3,3"
                 VirtualizingPanel.VirtualizationMode="Recycling"
                 ScrollViewer.IsDeferredScrollingEnabled="True"
                 ScrollViewer.CanContentScroll="True">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Border BorderBrush="Blue"
                            BorderThickness="5">
                        <Grid Width="{Binding DataContext.GridWidth,RelativeSource={RelativeSource AncestorType=UserControl}}"
                          Height="{Binding DataContext.GridHeight,RelativeSource={RelativeSource AncestorType=UserControl}}"
                          >
                            <Grid.Resources>
                                <Style TargetType="TextBlock">
                                    <Setter Property="FontSize" Value="50"/>
                                    <Style.Triggers>
                                        <Trigger Property="IsMouseOver" Value="True">
                                            <Setter Property="FontSize" Value="80"/>
                                            <Setter Property="Foreground" Value="Red"/>
                                        </Trigger>
                                    </Style.Triggers>
                                </Style>
                            </Grid.Resources>
                            <Grid.RowDefinitions>
                                <RowDefinition/>
                                <RowDefinition/>
                            </Grid.RowDefinitions>
                            <TextBlock Text="{Binding Time}" Grid.Row="0"/>
                            <TextBlock Text="{Binding ISBN}" Grid.Row="1"/>
                        </Grid>
                    </Border>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</UserControl>


//ViewAViewModel.cs
using Prism.Events;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;

namespace WpfApp21.ViewModels
{
    public class ViewAViewModel:BindableBase
    {
        private readonly IEventAggregator eventAggregator;
        public ViewAViewModel(IEventAggregator eventAggregatorValue)
        {
            eventAggregator=eventAggregatorValue;
            eventAggregator.GetEvent<BookChangedEvent>().Subscribe(OnBookChanged,
                ThreadOption.PublisherThread,
                false);
            SetSize();
            BooksCollection = new ObservableCollection<BookPayload>();
        }

        private void OnBookChanged(BookPayload payload)
        {
            BooksCollection.Add(payload);
        }

        private void SetSize()
        {
            var mainWin=System.Windows.Application.Current.MainWindow;
            if(mainWin != null )
            {
                GridWidth = mainWin.ActualWidth/4*3;
                GridHeight = mainWin.ActualHeight / 5;
            }
        }

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

        private double gridWidth;
        public double GridWidth
        {
            get
            {
                return gridWidth; 
            }
            set
            {
                SetProperty(ref gridWidth, value);
            }
        }

        private double gridHeight;
        public double GridHeight
        {
            get
            {
                return gridHeight;
            }
            set
            {
                SetProperty(ref gridHeight, value);
            }
        }

        private string viewAStr;

        public string ViewAStr
        {
            get
            {
                return ViewAStr; 
            } 
            set 
            {
                SetProperty(ref viewAStr, value);
            }
        }
    }
}


//ViewB.xaml
<UserControl x:Class="WpfApp21.Views.ViewB"
             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:WpfApp21.Views"
             xmlns:prism="http://prismlibrary.com/"
             prism:ViewModelLocator.AutoWireViewModel="True"
             VerticalAlignment="Stretch"
             HorizontalAlignment="Stretch"
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <Button Content="Send"
                FontSize="100"
                Command="{Binding SendBookPayloadCommand}"
                />
    </Grid>
</UserControl>


//ViewBViewModel.cs
using System;
using System.Collections.Generic;
using System.Text;
using WpfApp21.Services;

namespace WpfApp21.ViewModels
{
    public class ViewBViewModel:BindableBase
    {
        ITimeService timeService;
        IGuidService guidService;
        private readonly IEventAggregator eventAggregator;

        public ViewBViewModel(ITimeService timeServiceValue,IGuidService guidServiceValue, 
            IEventAggregator eventAggregatorValue)
        {
            timeService = timeServiceValue;
            guidService = guidServiceValue;
            eventAggregator = eventAggregatorValue;
            SendBookPayloadCommand = new DelegateCommand(SendBookPayloadCommandExecuted);
        }

        private void SendBookPayloadCommandExecuted()
        {
            var bk = new BookPayload()
            {
                Time = timeService.GetTimeNow(),
                ISBN = guidService.GetGuid()
            };

            //Get the event and publish it with the payload
            eventAggregator.GetEvent<BookChangedEvent>().Publish(bk);
        }

        private string viewBStr;
        public string ViewBStr
        {
            get
            {
                return viewBStr;
            }
            set
            {
                SetProperty(ref viewBStr, value);
            }
        }

        public DelegateCommand SendBookPayloadCommand { get; set;}

    }
}

 

posted @ 2025-09-30 16:36  FredGrit  阅读(13)  评论(0)    收藏  举报