Prism 4 Document---10th chapter sharing code between Silverlight and WPF

Source: Internet
Author: User
Tags silverlight
This topic helps you understand the multi-objective and its pros and cons from Prism. The multi-target code has roughly the same code base for two different platforms. This allows you to keep the code as much as possible to produce binary files for two different technologies. In this case, the techniques described in this section are WPF and Silverlight. This topic contains some considerations when you are using these technologies to develop multi-target applications. goals and a littleWhen writing WPF and Silverlight applications with similar capabilities and capabilities, it is meaningful to work with a code base. Although WPF and Silverlight platforms are very similar, they have limited binary compatibility.    Only a specific set of kernels referenced in SILVERLIGHT4, the portable framework assembly can be loaded into the runtime of. NET Framework4.0. Because Prism provides a lot of similar functionality for WPF and Silverlight. Many of the code can be generated for both of these technologies. Support for multi-target applications is primarily about the pattern and structure for implementing the possibility of maximizing the sharing of code and components between the two environments, as well as for allowing an application to integrate the environment-specific functionality so that it can take full advantage of the specific functionality of the desktop or browser. By creating a multi-objective composite application that uses prism, you can reuse the source code that spans WPF and Silverlight applications.

Out of Range

If you can organize your components to take full advantage of the binary compatibility support between Silverlight and WPF, you should do so.    For more information on this, the situation is published by the CLR team "sharing Silverlight assemblies with. NET Apps." This chapter is not intended to describe this scenario, instead it describes the challenges and solutions that are faced by building multi-target applications through shared source code.

Multi-Objective scenarios

The main scenario is for applications that offer both a feature-rich desktop experience and a wide range of Internet application experiences. In this case, you might want to develop applications for WPF and Silverlight or for a feature and workflow that provides the same functionality and workflow as a different one. Some of the following multi-objective applications:
    • You can provide users with a full-featured, browser-based version of the app in the office that can be scaled down when traveling.
    • You can provide an internal user with a desktop class application and a browser application for external people or participants.
For example, an enterprise might want to have an application that the user wants to place a call center on the phone and a customer who wants to place an order online. However, the form is completely different. The form of a phone call center Desktop Order provides more information and expanded functionality than the form of placing orders online.    However, as they accomplish something like this there will be certain parts of the order and business logic that can be reused across two scenarios. Service-oriented applications are more likely to achieve multiple goals because Silverlight is inherently service-oriented. Silverlight does not support local storage or access the database because of its target feature setting and security mechanism. In addition, connected applications are much easier to target because of the associated nature of Silverlight.

Thinking of multi-objective

With the multi-objective of the solution, you should also consider the following points:
    • Silverlight provides isolated storage on local client computers with limited storage space.
    • You may lose simplicity and legibility in the code in your multi-objective solution. Because some features of WPF are not implemented in Silverlight. You will need to solve these problems, and this will result in your code being no longer elegant or easy to read.
    • By default, Silverlight applications run in a secure sandbox, so there are a few things you can't do outside the sandbox environment. These apps have restricted access to the local computer and are limited to help prevent malicious behavior. These restrictions prevent access to the device and interact with other programs that are running.
Note: If you need to access some of these items, you can create a Silverlight application other than a browser that has elevated trust permissions. For more information, see "Trusted Applications" on MSDN
    • Silverlight only supports asynchronous communication, so you cannot use synchronous communication in multi-target applications.

Multi-Objective elements

Often there is a lot of code that has nothing to do with the actual presentation end. Because Silverlight and the. NET framework runtime are very similar in nature. Most of the code can be shared between the two technologies. This also encourages a large number of modes of demonstrating isolation to be separated from the actual visual presentation and presentation logic. To maximize the separation of UI and non-UI code. You can make the following multi-target source code elements:
    • Presentation mode. Patterns such as MVVM,MVP and MVC can be used if the logic is mostly the same between platforms.
    • Service. Services that help demonstrate can often be used for multiple goals.
    • Unit tests. Many unit tests can be multi-objective in a tool, such as a Silverlight unit test, and the framework can use the same property structure as MSTest.
    • A simple view. If XAML is used to support Silverlight and WPF. If a view consists only of basic controls and simple data binding, it may also be shared between WPF and Silverlight.
The Silverlight API is mostly a subset of the. NET Framework's APIs, so it is often meaningful to use this smaller API to develop applications to reduce the use of features that cannot be used concurrently across multiple platforms. Because of the differences between Siliverlight and WPF XAML, the following elements are more difficult to reuse:
    • Complex Views (XAML)
    • Controls
    • Styling
    • Animation
    • Expression Blend behaviors and triggers

A multi-Objective solution: multi-linked projects

Silverlight and WPF are only limited binary compatible, so some code combinations must be recompiled in each target environment. Prism uses mechanisms for providing guidance on the structure of the application and referencing the module code to multiple projects. Each project is managed by all references, resources, and code specified by the WPF and Silverlight target environment. The sharing of the code connected between the two projects allows them to be automatically compiled into their respective targets, and unit tests can be similarly shared between the two environments so that they can be written once in any target environment to run the target code. The Prism team created a tool called the Project Connector to help create and maintain these connections.    The Project Connector tool is used to connect projects in the Prism class library, Quick Launch, and implementation references.    Note: You can download the project connector from Visual Studio Gallery or open Visual Studio, and in the Tools menu, click Extend Management to find the project connector in the online library of the Extension Tools Management window. Non-UI code and components may be easier to share, so persisting in separating UI patterns is essential to ensure that the UI and non-UI parts of the application or module are clearly separated.

Core applications

The overall pattern is shared based on the application kernel code and is then augmented with extensions that implement WPF and Silverlight-specific features. The application's kernel defines the overall structure of the application and contains the code and components that are common in both environments.    Silverlight is a major subset of WPF, so developing an application kernel in Silverlight reduces the risk of relying on an API that is supported in WPF but not supported in SILVERLIHGT. Note: Many projects in the prism source tree actually own the kernel source files in the WPF project and connect the Silverlight project to the files of the WPF project.    This is mainly due to the historical reasons why the first version of Prism was built before Silverlight was released. The following illustration shows the resource manager for Multi-targeted QuickStart. Most of the WPF versions of QuickStart are connected files because the application's kernel is actually developed in Silverlight. The shared files found in QuickStart include pictures, modules, services, interfaces, and resources. The shared (connected) file is highlighted.

Create a multi-target application

This section describes three aspects to consider for developing multi-objective applications:
    • Design and coding guidelines. This section describes what to consider when sharing code between Silverlight and WPF.
    • Guidelines for the process. This section describes how the shared code between Silverlight and WPF is implemented.
    • Team building guidelines. This section describes the problem of building a multi-objective program that is specific to the unity of the software.
    • The contrast between Silverlight and WPF. This section describes the differences between Silverlight and WPF.

Design and Coding Guidelines

The design and coding policy contains the following elements:
    • Use the performance separation mode to maximize the number of shared code.
    • When possible, edit the code that can be compiled under two platforms. If not, follow these steps:
      • Use the # if label if you have a simple or single-line construction method.
      • Partial classes are used when most of the classes are similar but some methods have implementations of a specific platform
      • Use partial methods only when you need to invoke an external method on one platform but do not need to invoke an external method on another platform
      • To build a class of a specified platform with a single responsibility
    • Create your own solution folders for Silverlight and WPF
    • The refactoring code takes a long time for Silverlight and for WPF references.
These guidelines are described in more detail in the following chapters.

Maximizing the number of shared code using performance separation

Sharing views across platforms-code can be tricky. It will be easier if you say that logic code separates shared presentation and business logic from the UI. In addition, this makes the code more understandable and maintainable.

Write code compiled in two platforms

When possible, edit code that can be compiled under two platforms for reuse. When this approach becomes too complex, you have to weigh the use of two copies of code with a base class code with elegance. For example, in Silverlight, you can execute the following LINQ expression on the Items property of ItemsControl.
ItemsControl Someitemscontrol = new ItemsControl (); SomeItemsControl.Items.Add (new TextBox ()); bool Hasdependencyobjects = SomeItemsControl.Items.Any (item = Item = DependencyObject);
However, because the Items property in WPF is not ienumerable<t>, this implementation will not work properly. Instead of creating a different version in WPF and Silverlight, choose a lower preferred, but single-source solution, such as the following code.
ItemsControl Someitemscontrol = new ItemsControl (); SomeItemsControl.Items.Add (new TextBox ()); bool Hasdependencyobjects = False;foreach (var item in Someitemscontrol.items) {    if (item is DependencyObject)    {        Hasdependencyobjects = true;        break;    }}
This simple way is written in Silverlight because it is forced to use in the. NET framework.

If you have a simple or single-line construct using the # if declaration

Sometimes you can't have to create a single code base because of the incompatibility between WPF and Silverlight. In this case, you can use the # if Silverlight tag to create and fall into the compilation section. The following code example shows the use of # if Silverlight claims.
#if SILVERLIGHT            System.Windows.Application.Current.RootVisual = shell; #else            Application.Current.MainWindow = Shell;            Shell. Show (); #endif
However, #if有一些不好:
    • The code lacks legibility and ease of maintenance. If this # if declaration is hashed in your code, it becomes difficult to read and maintain.
    • Debugging becomes difficult. If there is a compilation error in the constructor method. When you try to open a file, Visual Studio chooses the solution that contains the physical file instead of the solution that contains the error, which means that you must manually close the file and then open the correct solution or edit the code without prompting.

Partial classes are used when most of the classes are similar but some methods have implementations of a specific platform

When the changes between Silverlight and WPF become more complex, you can create partial classes. Tag the shared class as part of the class and then create a partial class for the specific platform. This is also applied to the unit test. Here are some additional suggestions:
    • Try to keep the methods of a particular platform private. In this way, unit tests will not need to contain specific logic for a particular platform.
    • Ensure that classes have separate, clear responsibilities, and that any part of the classes written for a particular platform should refer to changing the detailed implementation content.
Note: If the differences between the two platforms become very wide, and the classes of the two platforms become very different, consider creating classes of the specified platform to replace the partial classes. The following sample code shows a partial class, Realestateservice, that is shared in Silverlight and WPF projects in the multi targeting QuickStart project.
namespace realestatelistingviewer.services{public    partial class Realestateservice:irealestateservice    { Public        realestate getrealestate ()        {            ...            return property;        }    }
The following code example shows the retrieval of a picture in a section of the class named Silverlight in the Realestateservice class in Multi-targeting QuickStart.
namespace realestatelistingviewer.services{public partial class Realestateservice {//<summary> Return the images.        In Silverlight, you want to download the image///from a Web server.         You can either store the images in the server or build AN//HTTP handler to retrieve the images.            </summary> private static BitmapImage GetImage () {Uri Imageuri;            Uri Source = App.Current.Host.Source; if (source. ToString (). StartsWith ("file://", StringComparison.OrdinalIgnoreCase)) {Imageuri = new Uri (":            /images/house.jpg ", urikind.relative); } else {Source = new Uri (string. Format (CultureInfo.InvariantCulture, "{0}://{1}:{2}/", source.) Scheme, source. Host, source.                Port));            Imageuri = new Uri (source, "images/house.jpg");        } return new BitmapImage (Imageuri); }    }}
The following code shows the retrieval of a picture in a partial class of WPF specified in the Realestateservice class in Multi-targeting QuickStart.
namespace realestatelistingviewer.services{public    partial class Realestateservice    {//        <summary >//        Return the images. In a Windows application, normally you//        retrieve the image from a database        . But for simplicity, it's just being retrieved from the file system.        </summary>        private static BitmapImage GetImage ()        {            return new BitmapImage (New Uri (".. /images/house.jpg ", urikind.relative));}}}    
use partial methods only when you need to invoke an external method on a platform other than a platformIf some work needs to be performed only in Silverlight or only in WPF. You can also use some of the methods. This means that you can put the interface of a method into the parent class and put the implementation of the interface into the class of the specified platform only. For another platform, the compiler will remove the method call. Here are some of the limitations of the method:
    • The declaration of a partial method must start with the partial keyword and the return type must be void.
    • Some methods can have ref parameters but cannot have out parameters
    • Part of the method is implicit private, so it cannot be virtual.
    • Some methods cannot be extern, and the introduction of the rendered theme determines whether they are defined or implemented.
    • Some methods can have static and unsafe modifiers
    • The partial approach can be traditional. Constraints are defined in the declarations of partial methods and can optionally be repeatedly defined in the implementation. parameter and type parameter names do not have to be identical to the defined names in the implementation.
    • You can not assign a delegate to a partial method.

To build a class of a specified platform with a single responsibility

In general, it is more meaningful to put code that affects all of the specified platforms into a separate class (for example, a service or service proxy). If most of the logic is different in two platforms, that will happen. In this way, you can create an implementation of a specified platform for the service, such as a fetch data cache, or authorization. This approach can also work in situations where only one platform can provide functionality. Here are some additional suggestions:
    • Use common interfaces in different platforms to share code. For example, in the Prism class library, there are several classes of specific platforms for loading module types, such as xapmoduletypeloader for Silverlight and Filemoduletypeloader for desktop programs. Their heads implement the Imoduletypeloader interface.
    • When you share some functionality in different platforms, it is advantageous to compose the overall inheritance (for example, using policy mode). In other words, determine whether it is beneficial to break out code with a particular feature share in a shared class. In some cases, it is meaningful to use inheritance.

Create your own solution folders for Silverlight and WPF

Use the solution folder to keep your solution organized. Typically, you can do this by using two folders, enabling one for Silverlight code and the other for WPF code. For example, how to organize the structure of your application and view multi-targeting QuickStart.

To check Silverlight and WPF references when refactoring code

Sometimes, a Silverlight reference might fall into a WPF project and vice versa. This is caused by the use of refactoring tools. If you get an unexpected compiler error about a Silverlight component that is not referenced in a WPF project, check the reference.

Process Guidance

Process guidance includes the following:
    • Develop the kernel in Silverlight.
    • Connect shared code between the source project and the target project.
    • Use the same namespace for Silverlight and WPF projects.
These instructions will be described in detail in the next sections.

Developing the application kernel in Silverlight

Since Silverlight is a major subset of WPF, the same code can run without major changes in WPF, so you should develop the application kernel in Silverlight.

To connect shared code between a source project and a target project

For those files that are common to Silverlight and WPF but require different references, you should use the connection file. One approach is to use the Project Connector tool to connect shared code between the source project and the target project.

Using the same namespace in Silverlight and WPF projects

Because shared code requires the same namespace, keep the namespaces between projects the same.

Team Building Guidance

This section will describe the team building guidance.

Configure the team build in the build ground

If you use team building to build a solution to host WPF and Silverlight projects, you may encounter file conflict issues. By default, Team build will copy the output from the project to a separate output folder.    Because WPF and Silverlight projects should have the same output name, there will be file conflict issues to organize you to compile your project or run unit tests.    By setting the Customizableoutdir property to True, you can build a high number of team builds to a location instead of copying the output to a separate location, which will prevent name collisions as a challenge. In addition, if you set this property and want to run unit tests in your build, you also need to specify the location of the testcontainers.
 <PropertyGroup><!--Build in Place-->  <CUSTOMIZABLEOUTDIR&G T;true</customizableoutdir>  </PropertyGroup> <!-override the beforetestconfiguration target To specify where the Testcontainers live. --<target name= "Beforetestconfiguration" > <!--change the OutDir, because the TestToolsTask needs T The tests-->  <propertygroup>   <outdir>$ (solutionroot  ) \source\</outdir>   </propertygroup>  <!--Create A list of all tests DLLs ' s to Run (test only, the desktop versions)-->  <createitem include= "$ (solutionroot) \**\desktop\**\bin\debug\%2 A.tests.dll   <output itemname= "TestContainer" taskparameter= "Include"/>   </createitem>  </target> 
Note: This example assumes that your desktop item is placed in a folder named Desktop. MSTest.exe can run unit tests only when the target desktop version is the. NET framework. So the Silverlight test assembly is executed.

Silverlight and WPF contrast

Both Silverlight and WPF allow you to develop applications based on the XAML and. NET framework that enrich the user experience.    However, there are some differences between the two platforms, and these differences need to be carefully considered when it comes to being overly over between Silverlight and WPF programs or when building a target that includes WPF and Silverlight applications. Note: This topic describes the differences between SILVERLIGHT4 and the. NET Framework 4.0 that are part of WPF. These differences are expected to decrease in the future version.

Silverlight and WPF Architecture overview

WPF provides developers with a unified programming model for building rich forms applications, including UI, media, and documentation.    WPF enables software developers to provide a new level of "user Experience" (UX) by providing a declaration-based language (XAML) that specifies vector-based graphics that can extend and take full advantage of hardware acceleration. Silverlight is a cross-browser, cross-platform implementation. The NET Framework provides the next generation of rich interactive media and content through the Web, desktop business applications and browser-hosted rich Internet Applications (RIA) that can integrate data and services from many sources. Silverlight allows developers to build applications that significantly enhance a typical end-user experience compared to traditional Web applications.    Like Wpf,silverlight provides a XAML-based language to specify the user interface. Silverlight and WPF share many of the same features and features, but they are built at the top of different runtime stacks, which is the following illustration. WPF leverages the full. NET framework and the execution of the common language runtime (CLR). Silverlight is a subset of XAML-based, complete. NET Framework, and executes in different versions of the CLR.

The difference between Silverlight and WPF

To keep Silverlight small and lightweight, some WPF and. NET framework features are not available in Silverlight. Because of this, it may be subtle and less subtle that the difference is to be considered carefully when building an application for WPF and Silverlight, or over-application between Silverlight and WPF. This section describes some of the major differences that are encountered in developing prism in the prism team. These differences are for SILVERLIGHT4 and WPF 4.0, which are currently written in the version. ResourcesA resource is a simple collection of key-values that can store almost any element (string, brush, style, data source, and many others). Resources can be associated to almost any element class that exposes the Resoures property of the ResourceDictionary type. Here are some of the differences between Silverlight and WPF about resources: resources can contain static or dynamic content. Dynamic content can be changed at run time and the consumer of the resource will be automatically updated. Dynamic resource references are not supported in Silverlight, so only static resource references are available.

Trigger

Triggers allow the designer to define the visual behavior of the control, and declaratively specify how its properties change when the event or property changes, such as highlighting a button when a button is clicked. Typically, triggers are triggered when the property of a control changes, causing one or more properties of the control to change.    Triggers are defined inside the style and can be applied with any object of the specified target type. Silverlight does not support Styles,controltemplates, or datatemplates (the Triggers collection does not exist with these elements) triggers. However, similar behavior can be achieved by using Silverlight's visual state Manager (VSM) to define control template interactions. Using VSM, the visual behavior of the control, including any animations and transformations, is defined in the template of the space. These can be easily done in the Blend4.    However, to know that XAML files will become more complex and that the templates built into Silverlight are not compatible with WPF. The blend SDK provides the blend behavior for animations and the visual state Manager can be used in a consistent look and feel for WPF and Silverlight applications. Data BindingBoth WPF and Silverlight provide support for data binding. The following are the main differences in data binding between Silverlight and WPF:
    • In Silverlight, the OneWayToSource data stream mode is extinguished
    • In Silverlight, you cannot bind directly to XML data. One possible workaround is to convert the XML to a CLR object and then bind to the CLR object.
    • In Silverlight, there is no Xmldatprovider class.
    • In Silverlight, there is no Datatemplateselector class. In WPF, this class provides a way to select DataTemplate based on data objects and data-binding elements. However, in order to support a specific MVVM scenario, Prism provides a similar function for Silverlight in its Datatemplateselector class.

Command

Here are some of the different things about commands in WPF and Silverlight:
    • Command not available in Silverlight middle. However, the ICommand interface can be used in Silverlight, allowing developers to create their own custom commands. The Prism Class Library provides an implementation of the Delegatecommand and Compositecommand classes for simple commands.
    • In WPF, controls can connect to commands through their command properties. By doing this, the developer can declare the associated controls and commands. This also means that a control can interact with the command so that it can glide the command and make its state automatically updated. In Silverlight China, some controls support command commands, but not as many as WPF. For Silverlight controls that do not provide a command property, consider using the blend behavior to wake the command based on a trigger.
    • There are no loss gestures and input bindings in Silverlight.

Miscellaneous

The following are some miscellaneous differences between Silverlight and WPF:
    • In Silverlight, the UIElement class has an internal constructor, so you cannot create a control that inherits it.
    • In Silverlight, there is no support for x:type extension markup or for custom extension markup.
    • In Silverlight, there is no support for x:static extension markup or for custom extension markup. In Silverlight, children added to the TabControl control are not automatically sealed pretend like in WPF-a tabitem.
    • All of the Silverlight network calls must be asynchronous.
    • The Silverlight network, in addition to trusting browser applications, is for server client access policies other than the origin of the site server.

More information

   You can download the project connector from Visual Studio Gallery or open Visual Studio, and in the Tools menu, click Extend Management to find the project connector in the online library of the Extension Tools Management window. For more information on organizing the assembly structure to get the benefits of binary compatibility between Silverlight and WPF, see the blog published by the CLR team"Sharing Silverlight assemblies with. NET Apps":

Http://blogs.msdn.com/b/clrteam/archive/2009/12/01/sharing-silverlight-assemblies-with-net-apps.aspx

    For more information on the WPF architecture, see the"WPF Architecture":

Http://msdn.microsoft.com/en-us/library/ms750441.aspx

    For more information on the Silverlight architecture, see the"Silverlight Architecture" : 

http://msdn.microsoft.com/en-us/library/bb404713 (vs.95). aspx

For more information on the different summaries between WPF and Silverlight, see the"WPF Compatibility" on MSDN:

http://msdn.microsoft.com/en-us/library/cc903925 (vs.95). aspx

For more information about the visual state manager and how it works in creating controls, see the following article on MSDN to create a custom control:

    • http://msdn.microsoft.com/en-us/library/cc278064 (vs.95). aspx (for Silverlight)
    • Http://msdn.microsoft.com/en-us/library/ee330302.aspx (for WPF in. NET Framework 4)

For more information about creating an application that promotes trust, see the "Trusted Applications" on MSDN at MSDN:

http://msdn.microsoft.com/en-us/library/ee721083 (vs.95). aspx

Prism 4 Document---10th chapter sharing code between Silverlight and WPF

Large-Scale Price Reduction
  • 59% Max. and 23% Avg.
  • Price Reduction for Core Products
  • Price Reduction in Multiple Regions
undefined. /
Connect with us on Discord
  • Secure, anonymous group chat without disturbance
  • Stay updated on campaigns, new products, and more
  • Support for all your questions
undefined. /
Free Tier
  • Start free from ECS to Big Data
  • Get Started in 3 Simple Steps
  • Try ECS t5 1C1G
undefined. /

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.