Prism4 document translation (Chapter 9 Part 1)

Source: Internet
Author: User
ArticleDirectory
    • 9.1.1 create a PROXY command
    • 9.1.2 create a composite command
    • 9.1.3 make the command globally valid
    • 9.1.4 bind a Global Command
 
Because my laptop hard drive was completely broken by me, the rest of chapter 5, chapter 6, chapter 7, and chapter 8 have all disappeared into the sea, sorry for them. After completing chapter 9, 10, and 11, I will complete the content. I recently bought a new computer and updated my personal work schedule. Therefore, the translation time is temporarily set to-every night and will be released around. I will test run for 2 weeks on the schedule to observe the situation.
 
Starting from chapter 6 (although he is already far away), I will change the form of translation from the original mechanical translation to a certain order under the premise of guaranteeing the faithfulness and elegance, I will not intentionally add any personal opinions to it (unless I am not conscious of it, I cannot guarantee it), but will modify the original word order to make it more in line with Chinese reading habits. In addition, brackets are added to all areas of poor self-perception to illustrate my own opinions or translation methods. You are welcome to criticize and correct me. Thank you.
 
This section introduces:
 
This section describes how to use command, regieoncontext, and share service to provide communication between modules.
 
The wrong word was changed, and a few items were not clearly described. Today's plan was completed and we went to bed! 2012-2-2
 
 
 
 
Chapter 9 loosely coupled communication between components

When creating large and complex applicationsProgramThe common method is to divide it into several independent assemblies. At this time, minimizing the number of static connections will be more conducive to the independent development, testing, deployment and upgrade of modules. The key to achieving them is loose coupling interaction.

When inter-module communication is required, familiarity with the similarities and differences between each communication method will help to better determine the method used in a specific scenario. Prism provides the following communication methods:

LCommand. It is used to instantly respond to the expected interaction on the user UI.

LEvent aggregator. It is used for view model, presenters, and controller interactions that do not directly act on reaction.

LRegion context. This method provides context information between the view and its subjects. This method is similarDatacontextBut does not rely on it.

LShared Service. The user calls events in the service to provide messages to the receiver. If none of the preceding methods are applicable, use it.

9.1 command

If you need to respond to a user behavior, such as clicking an event trigger (such as a button or one item in the menu), and for example, the trigger can change its availability status according to the business logic, use the command.

Windows Presentation Foundation (WPF) providesRoutedcommandIt focuses on the connection between command triggers that provide menu items or buttons and the command subjects that respond to the current item in the visual tree that has focus.

Because I know very little about WPF, I have never used this class. I personally think there is a problem with the translation here. I cannot determine the target modified by the two attribute clauses, the original text is as follows. WPF provides routedcommand, which is good at connecting command invokers, such as menu items and buttons, with command handlers that are associated with the current item in the visual tree that has keyboard focus. my understanding is as follows:

Routecommand (is good at focused on) (connection command invokers with command handler connection command triggers and command body handler can be translated as a handler, understood as the subject should be okay. I have removed the alias) {That (used to modify command handler. I understand it as an Attribute Clause) (are associated with xx) (current item in the visual tree current item) that (this clause should indicate what is the current item) has keyboard focus]})

However, in some complex scenarios, the command subject is often a view model that is not associated with any elements in the visual tree or does not focus on specific elements. To achieve this, Prism provides the ability to call the corresponding delegate method during command execution.Delegatecommand, And can combine multiple commandsCompositecommand. These commands and built-inRoutedcommandAre different,RoutedcommandRoute commands to the visual tree, I think it would be better to translate the command into "routing to a node in the visual tree and its upper layer ). It enables commands to be triggered at a node in the visual tree, but processed at the upper layer.

CompositecommandYesIcommandSo it can be bound by the caller.CompositecommandYou can bind several sub-commands whenCompositecommandWhen triggered, all sub-commands are executed.

CompositecommandEnable status is supported.CompositecommandMonitorCanexecutechangedEvent. This event is triggered to the caller. The caller callsCompositecommandOfCanexecuteMethod to respond to this event. ThenCompositecommandRe-call all sub-commandsCanexecuteMethod to Determine whether execution can be performed. If there is a sub-commandCanexecuteReturnedFalse, ThenCompositecommandWill returnFalse, Then its callers are disabled ).

How can this content help cross-module communication? Prism-based applications provide some globalCompositecommandThey are all defined in shell, that is, these commands can all be cross-module, suchSave,Save all, AndCancel. The module can register their commands with these global commands and participate in their execution.

Note ]:AboutWPFRouted eventsAnd routed commands

Routed event (for routing events, see msdn) is an event that is handled by multiple listeners in the element tree. A common event is handled by only the objects that subscribe to the event. While the WPF-routed command hand over the command message from the UI node in the visual tree, those elements that are not in the tree cannot receive the message, because they only have a bubble relationship with the focus or a clearly defined target element. (Original article: Because [They represents the element outside the tree] Only bubble up or down from the focused element or an explicitly stated target element) routing events can be used for communication in the element tree, because the data in the event is saved in every element of the route. Each element can change event data, which will also be applied to its next node.

Therefore, you can use routing events in the following scenarios: Define command handlers or custom control classes in the root command.

9.1.1 create a PROXY command

To create a PROXY command, instantiateDelegatecommand(Field, which is the meaning of the data field in the class, but it is not nice to put it here, so instantiate a XXX field I translate to instantiate XXX object, the same as below ),IcommandAttribute form to expose it.

Public ClassArticleviewmodel: icationicationobject
{
Private ReadonlyIcommand showarticlelistcommand;

PublicArticleviewmodel (inewsfeedservice newsfeedservice,
Iregionmanager regionmanager,
Ieventaggregator eventaggregator)
{
This. Showarticlelistcommand =NewDelegatecommand (This. Showarticlelist );
}

PublicIcommand showarticlelistcommand
{
Get{Return This. Showarticlelistcommand ;}
}
}
9.1.2 create a composite command

Create a composite command and instantiateCompositecommandObject, add commands to it, and finallyIcommandAttribute form to expose it.

 Public   Class Myviewmodel: icationicationobject
{
Private Readonly Compositecommand saveallcommand;

Public Articleviewmodel (inewsfeedservice newsfeedservice,
Iregionmanager regionmanager,
Ieventaggregator eventaggregator)
{
This . Saveallcommand =New Compositecommand ();
This . Saveallcommand. registercommand ( New Saveproductscommand ());
This . Saveallcommand. registercommand ( New Saveorderscommand ());
}

Public Icommand saveallcommand
{
Get { Return This . Saveallcommand ;}
}
}
9.1.3 make the command globally valid

Generally, creating a globally valid command is instantiation.DelegatecommandOrCompositecommandAnd expose it in the form of static classes.

 
Public Static ClassGlobalcommands
{
Public StaticCompositecommand mycompositecommand =NewCompositecommand ();
}

In the module, associate the sub-commands with the sub-commands.

 
Globalcommands. mycompositecommand. registercommand (command1 );
Globalcommands. mycompositecommand. registercommand (command2 );

[Note]: to addCodeCreates a proxy class to access the global command (the same as in the global available command) and simulates the proxy class in the test.

9.1.4 bind a Global Command

The following describes how to bind a command to a WPF button.

<ButtonName= "Mycompositecommandbutton"Command="{X: static local: globalcommands. mycompositecommand}">Execute my composite command</Button>

Silverlight does not provideX: staticIn Silverlight, perform the following steps.

1. Create a public attribute in view model to obtain the commands in the static class, as shown below.

PublicIcommand mycompositecommand
{
Get{ReturnGlobalcommands. mycompositecommand ;}
}

2. Normally, the model passes the viewDatacontextAnd passed to the view (completed in the Post-view code ). The following code demonstrates how to bind a model to a viewDatacontext. After that, you can bind the command to the control in the view's XAML file.

 
View. datacontext = model;

3. Make sure that the following XML namespace has been added to the root node of the view XAML.

 
Xmlns: prism = "CLR-namespace: Microsoft. Practices. Prism. commands; Assembly = Microsoft. Practices. Prism"

4. Use in SilverlightClick. CommandThe additional property binding command to the button is as follows.

<ButtonName= "Mycommandbutton"Prism: Click. Command="{Binding mycompositecommand}"/>Execute mycommand</Button>

[Note]: Save the command as an app. XAML FileApplication. ResourcesResources. Then, set it in the view created after the settings take effect.Prism: Click. Command = "{binding mycompositecommand, source = {staticresource globalcommands }}"Event callers can also create global commands.

9.2 regional context

In many scenarios, you need to share context information in the main view of the region and the subview of the region. For example, a master detail (which I don't know how to translate) used to display the view of the business entity and an area used to display the additional information of the entity. PrismRegioncontextThe object is shared between the main view of the region and any view loaded in the region, as shown in.

 

Based on different scenarios, you can select a part of the shared data (such as the identifier) or the shared model. View will searchRegioncontextAnd then register change notification. View can also be changedRegioncontext. The following are some exposures and usageRegioncontext.

LRegioncontextCan be exposed to the region through XAML

LRegioncontextYou can expose the code to the region.

LRegioncontextIt can be used by the view in the region

[Note]: prism is only applicable to those in the region.DependencyobjectView accessRegioncontextSupportRegioncontextMust be a regionDependencyobject). If your view is notDependencyobject(For example, if you use the WPF automatic data module in the region to add a view model), you need to create a customRegionbehaviorTo enableRegioncontextPassed to the view object.

Note ]:Data context attributes

The concept of data context is to allow an element to inherit the information of the data source to be bound in its parent element. The child element automatically inheritsDatacontext. Data goes from top to bottom of the visual tree.

Therefore, the best way to bind a view model to a view in Silverlight is to useDatacontext; That is why in most casesDatacontextThe view model is stored in. This is because, unless the view is very simple, do not useDatacontextAttributes act as a loosely coupled communication mechanism between views.

9.3 Sharing Service

Shared Service is also a method for inter-module communication. When a module is loaded, the module adds its services to the service locator. Generally, a service is registered to a service locator as a common interface or retrieved from it. This allows the module to use the services provided by other modules without adding static references. Service instances are shared in different modules, so data can be shared between modules and messages can be transmitted.

In the stock trader reference implementation (an instance of stock trader Ri prism), the market module providesImarketfeedservice. The target module uses these services through the shell program dependency injection container. The dependency injection container provides the service positioner and parser. That meansImarketfeedserviceIt is used by other modules, so it can be used in Common AssemblyStocktraderri. InfrastructureBut the specific implementation of the service does not need to be shared, so it can be defined directly in the market module and can be updated independently.

To learn how these modules register services to the unity dependency injection container, see the marketmodule. CS file. Target ModuleObservablepositionThen, it is obtained through constructor injection.ImarketfeedserviceService.

 
Protected VoidRegisterviewsandservices ()

{

_ Container. registertype <imarketfeedservice, marketfeedservice> (NewContainercontrolledlifetimemanager ());

//...

}

shared services facilitate cross-module communication because service users do not need to establish static references with service providers. Services can be used to send or receive data between modules.

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.