Start with Prism learn WPF (vii) MVVM (iii) event aggregator Eventaggregator?

Source: Internet
Author: User

Original: Learn WPF from Prism (vii) MVVM (iii) event aggregator Eventaggregator?

Start learning WPF (i) WPF from Prism?

Learn WPF from Prism (ii) prism?

Learn WPF (iii) prism-region from Prism?

Start learning WPF (iv) Prism-module from Prism?

Starting with Prism learn WPF (v) MVVM (a) ViewModel?

Starting with Prism learn WPF (vi) MVVM (ii) Command?

Start with Prism learn WPF (vii) MVVM (iii) event aggregator Eventaggregator?

Event Aggregator Eventaggregator
  • Event aggregation. For communication across view models, presenters, or controllers when there are not a direct action-reaction expectation.

(⊙﹏⊙), Google a bit:

事件聚合。在没有直接的行动反应期望的情况下,跨视图模型,演示者或控制者进行通信。

1 are no direct action response expectations, 2 cross-view communication

Before you know the concept in detail, let's look at an example:

Through the introduction, it is easy to think of the chat window, when you enter text in a view a click Send, another view B will receive this message, and the text output to the screen, and at this time, view a does not care who will receive information, just submit, view B also no matter who sent the message, only receive, and display.

Close the door and put the code:

SETP1 in the Shell window, define two region, respectively, to show the send and receive views

    <Grid>        <Grid.ColumnDefinitions>            <ColumnDefinition />            <ColumnDefinition />        </Grid.ColumnDefinitions>        <ContentControl prism:RegionManager.RegionName="LeftRegion" />        <ContentControl Grid.Column="1" prism:RegionManager.RegionName="RightRegion" />    </Grid>

Today Typora updated, code block support xaml format, previously used xml-dtd , the following unified usexaml
Xaml

This should be the more complex XAMLthat appears in the tutorial, with a more detailed use of the grid, where the grid is much like a table, and you need to define the number of columns before using his layout, and the following code sets two columns for a grid

       <Grid.ColumnDefinitions>            <ColumnDefinition />            <ColumnDefinition />        </Grid.ColumnDefinitions>

So, can you add a line? That's for sure, here are two lines added for the grid, and the height of auto indicates that this line is adapted to the height of the content:

    <Grid.RowDefinitions>        <RowDefinition Height="Auto" />        <RowDefinition Height="Auto" />    </Grid.RowDefinitions>

When using the grid, you need to specify the grid location for the control, Grid.Column="1" 1 is the subscript, all starting from 0, 1 is the second column, when you do not specify a specific location, the default is to insert the control into the grid of 0 rows and 0 columns, above the LeftRegion first row of the column position.

SETP2 creates a new two module, which is used to send messages in Modulea and Moduleb,modulea, respectively, and views in Moduleb are used to receive display information.

The creation of the module has been explained in section Fourth

First look at the Send view of Modulea:

MessageView.xaml

    <StackPanel>        <TextBox Text="{Binding Message}" Margin="5"/>        <Button Command="{Binding SendMessageCommand}" Content="Send Message" Margin="5"/>    </StackPanel>

Messageview defines a text box, data binding, and then a button that binds a Sendmessagecommand command. When we click the Send Message button, the message is displayed in the Receive view.

Look at the display view of Moduleb:

MessageList.xaml

    <Grid>        <ListBox ItemsSource="{Binding Messages}" />    </Grid>

A listbox is defined to display the message. ItemsSource binding should be a collection, otherwise how to call the source?

Next, look at how prism implements cross-view model communication:

First, the definition of a MessageSentEvent class, inheritance PubSubEvent<string> , string is because the event receives the payload is a string type, the PubSubEvent<T> class is responsible for connecting the publisher and Subscribers, he is responsible for maintaining the subscriber list and processing events sent to subscribers.

using Prism.Events;namespace UsingEventAggregator.Core{    public class MessageSentEvent : PubSubEvent<string>    {    }}

Then we look at the Messageviewmodel:

using Prism.Commands;using Prism.Events;using Prism.Mvvm;using UsingEventAggregator.Core;namespace ModuleA.ViewModels{    public class MessageViewModel : BindableBase    {        IEventAggregator _ea;        private string _message = "Message to Send";        public string Message        {            get { return _message; }            set { SetProperty(ref _message, value); }        }        public DelegateCommand SendMessageCommand { get; private set; }        public MessageViewModel(IEventAggregator ea)        {            _ea = ea;            SendMessageCommand = new DelegateCommand(SendMessage);        }        private void SendMessage()        {            _ea.GetEvent<MessageSentEvent>().Publish(Message);        }    }}

First look at the familiar parts of us:

        private string _message = "Message to Send";        public string Message        {            get { return _message; }            set { SetProperty(ref _message, value); }        }

This is the <TextBox Text="{Binding Message}" Margin="5"/> message in the

And then define a delegatecommand.

public DelegateCommand SendMessageCommand { get; private set; }

The next step is the Eventaggregator section:

First define a ieventaggregator:

IEventAggregator _ea;

constructor function:

The EA is a eventaggregator instance provided by a dependency injection container and also defines a callback function for the command Sendmessagecommand SendMessage .

        public MessageViewModel(IEventAggregator ea)        {            _ea = ea;            SendMessageCommand = new DelegateCommand(SendMessage);        }

Sendmessge through Messagesentevent release payload, here payload must match messagesentevent of payload type, above we inherit PubSubEvent<string> the use of String , otherwise, This throws an exception at compile time.

        private void SendMessage()        {            _ea.GetEvent<MessageSentEvent>().Publish(Message);        }

Next, let's MessageListViewModel get this payload in Moduleb and do something about it:

using Prism.Events;using Prism.Mvvm;using System.Collections.ObjectModel;using UsingEventAggregator.Core;namespace ModuleB.ViewModels{    public class MessageListViewModel : BindableBase    {        IEventAggregator _ea;        private ObservableCollection<string> _messages;        public ObservableCollection<string> Messages        {            get { return _messages; }            set { SetProperty(ref _messages, value); }        }        public MessageListViewModel(IEventAggregator ea)        {            _ea = ea;            Messages = new ObservableCollection<string>();            _ea.GetEvent<MessageSentEvent>().Subscribe(MessageReceived);        }        private void MessageReceived(string message)        {            Messages.Add(message);        }    }}

Code reading:

        private ObservableCollection<string> _messages;        public ObservableCollection<string> Messages        {            get { return _messages; }            set { SetProperty(ref _messages, value); }        }

This is the <ListBox ItemsSource="{Binding Messages}" /> messages in which his type is ObservableCollection , specifically why ObservableCollection instead of list! Say it later.

        public MessageListViewModel(IEventAggregator ea)        {            _ea = ea;            Messages = new ObservableCollection<string>();            _ea.GetEvent<MessageSentEvent>().Subscribe(MessageReceived);        }

Here subscribe to messagesentevent, and processing payload, processing payload method is messagereceived, this method adds a record in messages.

Event aggregators can have multiple publishers and multiple subscribers.

As a subscriber, I want to subscribe to a specific type of payload, and in the last example I just want to subscribe to a message containing Brian's event, how to handle it? Prism implements a filter for the Subscribe method:

            _ea.GetEvent<MessageSentEvent>().Subscribe(MessageReceived, ThreadOption.PublisherThread, false, (filter) => filter.Contains("Brian"));

Filter is a Predicate<TPayload> filter , refer to predicate

Start with Prism learn WPF (vii) MVVM (iii) event aggregator Eventaggregator?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.