CHAPTER 1

image

What Is XAML?

This chapter is a “crash course” in Extensible Application Markup Language (XAML). If you are experienced in writing applications using XAML-based technologies, feel free to skim the chapter and pick the parts that interest you. If you don’t have experience writing XAML-based applications, then this chapter is a prerequisite for the rest of the book.

A Brief History of Windows User Interface Design

Before XAML was introduced to the development community, Windows desktop applications were mainly created using the WinForms technology. The WinForms design paradigm is similar to Visual Basic 6–style graphical user interfaces (GUIs) of old. You work within a what-you-see-is-what-you-get (WYSIWYG) interface that allows you to drag controls from a toolbox and drop them on the window.

Visual Studio serialized the user interface in the designer as C# code that contained object declarations for all user interface controls along with property values and other details required to represent the user interface. This meant that if you were working in an environment where the team was made up of designers and developers, collaboration between the two groups was difficult. If a designer wanted to apply a common theme to a user interface, they would often create bitmap mock-ups and divide the mock-ups into smaller bitmaps to be used for each control on the form. These bitmaps would then need to be applied to each control as some property, such as the background. This process was tedious and inefficient. Bitmap-based designs don’t scale well, and resizing the controls on a form caused the associated bitmaps to resize, which would often result in degraded image quality. Enter XAML.

Extensible Application Markup Language

XAML (pronounced “zammle”) is based on Extensible Markup Language (XML) and is for designing user interface layouts. XAML is known as a declarative language. It is almost always used in conjunction with another type of programming language known as an imperative language, such as C#, VB.NET, C++, and so forth.

XAML-based technologies covered in this book include the following:

  • Windows Presentation Foundation (WPF): XAML + C# + WPF assemblies
  • Windows 8.1/Windows Store development: XAML + C# + Windows Store assemblies
  • Windows Phone 8.1: XAML + C# + Windows Phone assemblies

Each of these technologies uses XAML in combination with another .NET programming language, such as C# or VB.NET, to create desktop, tablet, and mobile applications with stunning and unique user interfaces as well as elegant and intuitive user experience designs, which were nearly impossible to achieve prior to the introduction of XAML and WPF in .NET 3.0.

Since XAML is an XML-based declarative markup language, it adds a completely new paradigm to Windows-based user interface (UI) development. XAML is verbose and thus easily read by humans. This is helpful when you need to edit XAML by hand. Moreover, the XML basis of XAML makes it an easy language for which WYSIWYG editors can be created.

I know, I know—right now you are probably thinking, “XML may be easy to read, but what about the performance of my application? XML is too verbose!” This is true. XML can cause performance problems when parsing; however, the XAML parser will compile your XAML into a binary format called Binary Application Markup Language (BAML) that is used during the execution of your application. BAML drastically reduces the size of your XAML code, and this helps to eliminate the performance problems associated with traditional XML parsing. BAML is tokenized as well so that duplicate references throughout the BAML code can be replaced by much smaller tokens. This in turn makes BAML code even smaller and thus faster during application execution.

Separation of User Interface Concerns

One of the great things about this new user interface design paradigm is the synergy it provides between developers and designers. Unlike technologies of the past, XAML includes code-behind associations, although this is not a requirement. In contrast to WinForms, XAML does not require the designer to create a C# representation of the user interface. XAML is designed to be all that is needed to define the look and feel of your user interface. This aspect of XAML, along with important new features such as data binding, routed events, and attached properties, which we’ll discuss throughout the book, allows XAML-based applications to take advantage of user interface design patterns that allow the complete separation of the user interface design (XAML) and presentation layer logic (C#).

This book will focus on the Model-View-ViewModel (MVVM) design pattern, which will be covered in depth in later chapters. There are other design patterns that you can use with XAML based user interfaces that allow you to separate your user interface design from the presentation layer logic, and you should definitely look into some of them. Table 1-1 provides references to two other great design patterns that you should explore.

Table 1-1. User Interface Design Pattern References

Design Pattern Name

Reference URL

Model-View-Controller (MVC)

https://msdn.microsoft.com/en-us/library/ff649643.aspx

Model-View-Presenter (MVP)

https://msdn.microsoft.com/en-us/magazine/cc188690.aspx

Declarative vs. Imperative Programming

In declarative programming, the source code is written in a way that expresses the desired outcome of the code with little or no emphasis on the actual implementation. This leaves the framework to deal with parsing the declarative source code and handling the “heavy lifting” required to instantiate objects and set properties on the these objects, which are defined in the XAML elements.

Imperative programming is the opposite of declarative programming. If declarative programming can be thought of as declaring what the desired outcome is, imperative programming can be viewed as writing lines of code that represent the instructions of how to achieve the desired outcome.

A great example of a declarative language and an imperative language working together is XAML and C#. Whether you are developing a smart client desktop application using WPF, a Windows Store app for use with tablets such as the Microsoft Surface Pro, or a mobile application using Windows Phone, any of these applications can be developed using a mixture of XAML and C#.

Image Note  When it comes to the imperative .NET languages, you are not limited to C#. Depending on the target platform, you can use C#, VB.NET, and even F#. A search of the Internet reveals that C# is generally the language of choice when using WPF, Windows Store apps, and Windows Phone 8, so that’s the language we’ll use for the code examples throughout this book.

Let’s begin by looking at the declarative XAML markup used to define a WPF Window. Listing 1-1 shows a basic WPF Window with a grid and a button control written declaratively in XAML.

If you don’t have experience with XAML, don’t worry about the syntax. Instead, note the aspects of declarative programming. You see what looks to be an XML file that contains a root element called Window. The elements in XAML are associated with a class in which the parser will create an instance of the specified type during runtime. The attributes of these elements are directly linked to the properties of the object that the element represents.

The element has attributes as well as nested elements. The nested elements can also be used as property values of the parent element’s instance. For example, notice that there is a Grid element, and within the start and end of the Grid element tags, there is a Button element. Much like the other elements, the Button element has a nested TextBlock element. In this case, the TextBlock element represents an instance of the TextBlock type that is assigned to the Content property of the Button element’s object instance.

Perhaps an example will assist in explaining how elements defined in XAML and their attributes and nested elements are related to object instances and property values. Just as Listing 1-1 shows the XAML definition of a WPF window using declarative programming, Listing 1-2 contains C# code to build a WPF window imperatively, which is identical to the window created declaratively in Listing 1-1.

As you can see, the C# code is imperative, which means that the application is expressed in lines of code where each line illustrates how the control instances are created. It also shows the properties and the order in which the property values are set in order to accomplish the same WPF Window layout as in Listing 1-1.

Let’s compare this to the XAML in Listing 1-1. The declarative style of the XAML Window definition doesn’t require you to instantiate any control instances. Instead, you express the controls that you need as XML elements. Also, the Button element contains a nested element of type TextBlock, which in turn has a nested string value to be displayed as the text of the button. This is what is meant when we say that declarative code describes what should appear in the window, without the need for any implementation details like object creation. The XAML parser handles creating the required object instances (Window, Grid, Button, and TextBlock). The XAML parser also evaluates nested elements, and then it decides which property the nested object will populate.

As you can see, declarative XAML is very different from other .NET programming languages. However, it’s pretty impressive to see the parser make complex condition-based decisions about the objects and property values that are created/transformed when building the WPF Window output upon program execution. “Intelligent” XAML parsing combined with the power of the C# presentation layer logic (code-behind event handlers and view models), along with the domain logic and infrastructure code, explain why XAML and C# are a commonly used design combination for the technologies you will be using to build a solid, robust, loosely coupled, and highly testable line-of-business application throughout this book.

To Code-Behind or Not to Code-Behind?

The separation of concerns that XAML creates between the user interface design and presentation layer logic allows you to design loosely coupled, unit-test-friendly applications, which are much easier to create since XAML came along. This allows designers to develop the user interface with design tools such as Visual Studio or Expression Blend to create the XAML, leaving programmers to work simultaneously in C# to build the presentation layer logic to respond to user interactions as well as the code to update the user interface upon requests from the domain logic or from external systems.

XAML files have code-behind files that work almost exactly like WinForms and WebForms code-behind files. The difference is that a user interface can be created without adding any code to the code-behind file. In fact, there are many MVVM purists who will suggest you never write code in the code-behind files of your XAML-based projects. The main reason for this is to create a complete separation of concerns between your user interface design and the presentation layer logic. For example, in a WinForms application, you can specify a Button’s click event handler in the code-behind of the form. This tightly couples the presentation layer logic to the user interface. These types of dependencies create presentation layer logic that is hard to unit test. It also makes it harder to switch between different user interface platforms without reproducing the event handlers. Although you can do the same thing in XAML, there are better options to keep your user interface concerns separate from your presentation layer logic.

One option is to bypass the code-behind completely and use data binding to bind the Command property of a Button to an ICommand implementation in a separate class. These data-binding techniques can be expressed 100 percent declaratively in XAML, meaning that you are not tied to a specific code-behind file. This lets you write reusable view models that handle all presentation layer user interaction logic, and they are also easily unit tested. This now brings us to our discussion of the MVVM design pattern.

The MVVM Design Pattern

The MVVM design pattern is based on the Presentation Model design pattern. John Gossman created it specifically for XAML and WPF. The MVVM pattern allows you to separate your domain model’s business logic (the model) from the user interface (the view) by adding a layer of abstraction that encapsulates all of the logic required by the user interface, and it processes requests from the user to perform actions on, or retrieve data from, the model. When using MVVM, the view is represented by XAML. The view is directly dependent on the view model; however, the view model is view agnostic. You should not have any user interface elements or other dependencies related to the view in the view model. The view model’s public interface should be well defined. Any change to the view model’s public interface could result in a change of the view. The view model will work with the application service layer to modify or retrieve data from the model. The model or domain model should only contain code that is relative to the business domain at hand. It’s important not to allow any of the user interface–related code from the view or view model to sneak its way into the domain model. The domain model should be isolated from any code that does not relate to the business domain. See Figure 1-1, which represents the communication between the different parts of the MVVM design pattern.

9781430267768_Fig01-01.jpg

Figure 1-1. The flow of communication when using the MVVM design pattern

As you can see, the view will declaratively create an instance of the view model. The view model’s properties will be data-bound to controls declared in the view. The data binding will allow for automatic updating of view control display values as well as binding user interface control events and commands related to user interaction to the methods and properties of the view model. The view model will respond to user interaction events to interact with the model. The view model will communicate with the model to make changes and report updates to the model. This allows for a complete separation of the user interface, presentation layer logic, and domain model of your application.

Basic MVVM Implementation in WPF

In this section, you will see how to create a bare-bones MVVM implementation using WPF and C#. This example will illustrate the key concepts of the MVVM design pattern. The view will be represented as a WPF Window. The view model will contain properties that provide data to display in the view using data binding. Notice that there is no code-behind needed; only XAML, the view model, and the model, which represents a class called PersonModel, are required. Remember that this is a basic example of MVVM, so don’t be concerned if you don’t understand everything in the example. There will be many more examples and explanations throughout this book. Listing 1-3 displays the WPF application markup.

As you can see, the Application class can hold application-level resources such as styles and templates. The main purpose for the Application class in this example is to provide the main startup object of the application, which is specified in the StartupUri attribute. Next up is Listing 1-4, where you see the definition of the MainWindow.xaml file, which represents the view.

Here you have a WPF window with two Grid objects for controlling the layout of the TextBox and TextBlock elements. You add a new XML namespace (xmlns:vm) and, instead of referencing a uniform resource identifier (URI), you reference the namespace of the view model. Now you can access any class defined under that namespace in XAML. In the Window.Resources element, you add a resource to the view model and give the resource a key value of viewModel so that you can access the resource in XAML. You set the DataContext property equal to the viewModel resource. Now, when you use data binding on other controls in the Grid, the binding will reference a property on the view model by the same property name. Now take a look at Listing 1-5, which is the source code for the model class.

As you can see, the model is simple. It represents a Person entity. There are two properties exposed, FirstName and LastName. The class implements the interface InotifyPropertyChanged, which allows the model to alert the view model of any property changes. Finally, Listing 1-6 shows the source code for the view model class.

The view model’s source applies the same techniques as the model. You implement the INotifyPropertyChanged interface to alert the view of changes to the properties (via data binding). You also include a new property named FullName, which will return the first and last names when one of those values changes. The first and last names are represented as TextBox controls in the view, so their values can be changed. The FullName property is represented by a TextBlock, which means that the user can’t modify the value. Nevertheless, because of the data binding to the view model, you can instantly see the FullName TextBlock’s Text property change when you modify either the TextBox for the first or last name.

Summary

In this chapter, you looked at the XAML language. We talked about the differences between declarative programming and imperative programming and how both can work together using XAML and C#. We touched upon data binding and the MVVM design pattern, which allows you to separate the user interface definition (view), the user interaction logic (view model), and the domain business logic (model) using the view model abstraction.

In the next chapter, you will look at some of the design patterns and other design techniques that you’ll use to create a line-of-business application that can share code between WPF, Windows Store, and Windows Phone.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.70.185