Tag Archives: visual c# tutorial visual c# 2010

The WPF Layout System – Visual C#

Layout in WPF is flow-based, but it also includes automatic resizing and repositioning of controls if the user changes screen resolution or resizes the window containing controls or adds or removes controls at runtime. As you will see in this chapter, this provides resolution and size independent user interfaces.

A window can contain one element, or control. That element will almost always be a container. A container contains controls and, optionally, other containers. All container controls derive from the System.Windows.Controls.Panel class. Layout in WPF is a recursive process. The .NET Framework runtime makes two passes before drawing elements.

In the Measure pass, the runtime queries each element to determine the element’s size and location. In the Arrange pass, the runtime determines the actual size and position for each element. Elements may or may not be sized and located where they requested, depending on the number of elements, the screen resolution, the size of the window, etc.

Layout is not only a recursive process, but it is also an iterative process. The entire layout process occurs each time the user resizes the window or your code adds or removes elements. You should keep this in mind as you design user interfaces.

How does the layout system determine how to size each element? Each element on a window is surrounded by a bounding box, as shown in Figure 1. This represents the space allocated to the element, and therefore represents the maximum size of the element.

helloworld

Figure 1 Each element on a window is surrounded by a bounding box.

The layout system determines the actual size of an element by taking into account the following:

  •  The available screen space.
  • The size of any constraints, such as maximum or minimum height or width.
  •  Layout-specific properties, such as alignment, margins, padding, etc.
  •  The behavior of the parent container.

As needed, the layout system can shrink, grow, or move elements on a window.

Alignment, Margins, and Padding

All elements have four properties that are important to understand, as these play a key role in determining the position of elements in a window. These properties are HorizontalAlignment, VerticalAlignment, Margin, and Padding. Alignment refers to how child elements should be positioned within a parent element’s allocated layout space. The HorizontalAlignment property determines how an element is positioned horizontally within a container. The possible values for this property are Left, Right, Center, and Stretch, as shown in Figure 2. If this property is set to Stretch, which is the default, the control will expand to its maximum available width.

WPFLayoutSystem2

 Figure 2  The HorizontalAlignment property determines how an element is positioned horizontally within a container.

The VerticalAlignment property determines how an element is positioned vertically within a container. The possible values for this property are Top, Bottom, Center, and Stretch, as shown in Figure 3. If this property is set to Stretch, which is the default, the control will expand to its maximum available height.

WPFLayoutSystem3

Figure 3. The VerticalAlignment property determines how an element is
positioned vertically within a container.

The Margin property determines the distance between an element and its child or peers. This property consists of four parts: the left margin, the top margin, the right margin, and the bottom margin. The following XAML sets the margin for an element following this pattern:

<Button Margin=”0,10,0,10″…

The previous code specifies that there should be no additional space on the left and right, but there should be a ten pixel space on the top and bottom. If you want the same margin on all four sides, you only need to specify one value. The following XAML sets the margin to ten on all sides:

<Button Margin=”10″…

The Padding property is similar to the Margin property, however it is only available for certain controls, including Border, Button, and TextBlock. The property adds space between the edge of a control and its content.

Figure 4 shows the use of the Margin and Padding properties, along with horizontal alignment, to control the layout of elements.

WPFLayoutSystem4

Figure 4. You can use the Margin and Padding properties, along with horizontal
alignment, to control the layout of elements.

Containers

As mentioned earlier, each window can contain a single element. This element will typically be a container control. This chapter covers the following containers:

  • StackPanel: Stacks elements horizontally or vertically.
  • WrapPanel: Places elements in rows and columns that wrap as needed.
  • DockPanel: Aligns elements along an edge.
  • Grid: Places elements in rows and columns.
  • Canvas: Places elements according to coordinates.

This post is an excerpt from the online courseware Windows Presentation Foundation Using Visual C# 2010 course written by expert Ken Getz and Robert Green.

Ken Getz is a Visual Studio expert with over 25 years of experience as a successful developer and consultant. He is a nationally recognized author and speaker, as well as a featured instructor for LearnNowOnline.

Robert Green is a Visual Studio expert and a featured instructor for several of our Visual Basic and Visual C# courses. He is currently a Technical Evangelist in the Developer Platform and Evangelism (DPE) group at Microsoft. He has also worked for Microsoft on the Developer Tools marketing team and as Community Lead on the Visual Basic team. Robert also has several years of consulting experience focused on developer training, and is a frequent speaker at technology conferences including TechEd, VSLive, VSConnections and Advisor Live.

Introducing Windows Presentation Foundation – C# 2010

Modern applications require a modern user interface. On the other hand, applications you create using Windows Forms, the standard user interface design package that Visual Studio has provided for past versions, look little different than applications written using tools you might have used in 1995.

No matter how you dress them up, forms created using the Windows Forms package generally look pretty much the same, as shown in Figure 1. Although you can create other types of applications, using Windows Forms, you’re on your own—the tools exist to create more creative forms, but you must write all the code for each application. You can create non-rectangular forms; you can create forms that scale. But you’ll write a lot of code to make it happen.

WPF1
Figure 1. It’s an attractive form, but it looks like every other form.

Although Windows Forms provide a rich set of tools for creating business applications, the package leaves a great deal to be desired for building intricate, rich, modern graphically oriented applications.

What if you want to create an application that uses a completely new type of interface? Perhaps you don’t want rectangular controls, but rather, would like to use your own styles?

One thing is for sure: If you’ve ever seen anyone use a computer interface in a movie or television show, you can be assured that you weren’t seeing an application created using Windows Forms. As you know, creating a visually appealing application using Windows Forms can be challenging. To be honest, up until recently, computer graphics hardware really wasn’t powerful enough for a forms package richer than Windows Forms. You can certainly use Windows Forms to create interfaces as you might see in a movie, but it’s not easy, and each application you write would require its own set of tools.

In addition, using Windows Forms, three-dimensional graphics were extremely difficult without using external libraries. Even then, your code was at the mercy of hardware that might not provide the power necessary to perform the required mathematical calculations. In addition, the underlying graphics engine, built into Windows for many years, is extremely limited.

Windows Presentation Foundation (WPF) provides a new design medium. WPF has been created from the ground up to take advantage of hardware power, and provides a consistent, powerful graphics platform. WPF includes an integrated, vector-based (as opposed to pixel-based) composition engine, which utilizes the power of the computer throughout the graphics stack. In other words, it takes advantage of both the processing power of the computer, and of the GPU (Graphics Processing Unit) built into the graphics hardware. WPF provides full support for resolution independence—as you move from one screen resolution to another, your WPF applications scale appropriately.

WPF introduces a unified approach to user interface, documents, and media: it provides full support for mixing all types of user interaction in a single application. Retrieve input from a user, display a movie, render the contents of a newspaper, all within a WPF application using native controls and rendering support.

From a programmer’s perspective, WPF makes rich document integration part of the development experience. Unlike Windows Forms, where you can bolt on media support, this support is simply part of WPF. In addition, WPF fully supports separation of design and code, allowing you to bring designers directly into the development process. Because you can use declarative coding to create your WPF applications, designers can create the user interface with either Visual Studio or other WPF-enabled tools (such as Microsoft’s Expressions products), and then you, as a developer, can add the programmatic functionality later. Finally, deployment of WPF applications is easy; it allows administrators to deploy and manage applications securely.

This post is an excerpt from the online courseware Developing Applications with Entity Framework 4.1 Using C# 2010 course written by expert Ken Getz and Robert Green.

Ken Getz is a Visual Studio expert with over 25 years of experience as a successful developer and consultant. He is a nationally recognized author and speaker, as well as a featured instructor for LearnNowOnline.

Robert Green is a Visual Studio expert and a featured instructor for several of our Visual Basic and Visual C# courses. He is currently a Technical Evangelist in the Developer Platform and Evangelism (DPE) group at Microsoft. He has also worked for Microsoft on the Developer Tools marketing team and as Community Lead on the Visual Basic team. Robert also has several years of consulting experience focused on developer training, and is a frequent speaker at technology conferences including TechEd, VSLive, VSConnections and Advisor Live.

Adding and Removing Page Elements with jQuery

Not only can you change the appearance of the page with jQuery and update the content of elements on the page, you can even add and remove elements to and from the page dynamically! Now, we’re talking real power: you can essentially rewrite the page on the fly using jQuery. Of course, you have long been able to do this using plain JavaScript, but it would take a lot more code and work, and you’d have to deal with nasty cross-browser issues.

The html method you learned about in the last section has rudimentary support for adding new elements to a page, embedded within a string. But that technique requires that you build a string containing the new elements. The difference between that technique and the ones you’ll learn about in this section is that with these new techniques you can add a new element anywhere on the page, before or after existing elements, without building a string first. It’s much more flexible and efficient this way.

jQuery has a few methods for adding elements, and one to remove elements. (There are a few others that can add and remove content, but this section focuses on the primary, most straightforward techniques.)

  • The insertBefore and insertAfter methods insert the new element you define immediately before or after all the elements in the wrapped set, as the sibling of each element. (A sibling is an element at the same level in the DOM hierarchy, with the same parent element, as another element.)
  • The prependTo and appendTo methods insert the new element you define as the child of each element in the wrapped set, either at the beginning or at the end of the child content.
  • The remove method removes all elements in the wrapped set from the page.

It is important to understand that adding and removing elements change only the in-memory DOM used to render the page, and leave the page source unchanged and unaffected.

One of the many ways you can make use of dynamically adding and removing elements is to handle the case where JavaScript is not available in the user’s browser, whether because the browser doesn’t support it or the user has it turned off. For example, you may build a page like the one shown in Figure 1 that has a highlighted notice at the top of the page along with a second paragraph that JavaScript code removes when the page loads. Therefore, if the browser doesn’t have JavaScript available, the notice and second paragraph remains on the page.

the page when javascript is not available

Figure 1. The page when JavaScript is not available.

For users that have JavaScript available and enabled, there are several changes to the page, as you can see in Figure 2. The JavaScript notice and following paragraph are removed, a secret message appears, a button that can hide content appears, and NOTICE!/END NOTICE! is added to the beginning and end of every paragraph. The page is quite different from its non-JavaScript version!

the page when javascript is available

Figure 2. The page when JavaScript is available and enabled.

If the user clicks the button, code in the page removes both the button and the snarky paragraph about everyone being able to see the content, as shown in Figure 3, leaving behind only the Michael Pollan quote with good advice about eating habits. Non-JavaScript users don’t have the capability of removing that content. As you can see the page demonstrates a number of different scenarios for controlling content through code using jQuery.

The following HTML code defines the starting content of the page in the body section (we’ve removed some of the text content to make it easier to focus on the structure of the page). Notice that one p element has a class associated with it, and the other two have an id value.

The noJavaScript CSS class, defined in the page in a style element rather than in a separate stylesheet, adds the red border and yellow background to the first paragraph.

The first block of JavaScript code in the page makes all of the initial changes to the page when it loads, and is enclosed in the jQuery ready function. Keep in mind that none of this code executes when JavaScript is not available.

The first part of this block of code uses the remove method to remove the highlighted notice and the following paragraph, using selectors appropriate to select those elements. That’s how easy it is to remove elements from the page! And if the selectors selected multiple elements, all those elements would be history.

The next statement dynamically adds the paragraph with the secret that only users with JavaScript enabled will be able to see. Notice that this statement uses a new form of the jQuery function, passing the HTML markup in a string as the sole argument to the function. This causes jQuery to parse and select the markup—as it does with a regular selector—but doesn’t yet insert it into the DOM. The insertAfter method takes care of that task, inserting the new paragraph immediately after the h1 element as its sibling. The argument to the method is a selector that selects the elements on the page that you want to place the new paragraph after. On this page, it will insert a single instance of the paragraph after the sole h1 element on the page.

NOTE: If there were more than one h1 element on the page, the insertAfter method call would add the new paragraph immediately after each of the h1 elements. You can easily test this by adding more h1 elements on the page. If you really only want one instance of the paragraph on the page, you’d need to change the selector that you pass to the insertAfter method, such as by using the :first filter.

The next statement dynamically adds the button to the page. The string defining the button is again passed to the jQuery function, but this time the code uses the insertBefore method to insert it immediately before the p element with an id value of everyone.

The final two statements in the first code block take care of adding the NOTICE!/END NOTICE! to the beginning and end of all p elements on the page. It is important to understand that at this point, there are only two p elements on the page; the others have been removed. That’s why back in Figure 2 only two paragraphs are visible. This code uses the prependTo method to insert NOTICE! at the beginning of each paragraph, and the appendTo method to add END NOTICE! at the end of each paragraph, with spaces needed to keep the new text separate from the old.

The second and final code block on the page wires up the click event function of the Remove Non-Sensitive Content button, buttonRemove, that the code added dynamically in the other code block. The event function does two things: removes the paragraph that contains “ hip ” (with leading and trailing spaces to avoid matching that string embedded in words) and removes the button.

The one big thing that is different in this code is that it passes a jQuery filter to the first remove method. Without that filter, the statement would remove all p elements on the page. But by filtering the wrapped set passed to the remove method by the jQuery function in that statement, it filters the p elements to be removed to only those that contain the hip string. In this statement you could easily have included the filter in the selector in the jQuery function, but in more complex, chained statements that might not have been possible. JQuery is a very flexible library indeed.

NOTE: The code that wires up the buttonRemove click event function didn’t have to go into its own jQuery ready function. It could have gone into the other code block, immediately after inserting the button to the page. It’s just personal style to keep event function definitions separate to make the code a bit cleaner and easier to maintain, but there really is no compelling reason to do so. Do it however works best for you.

One of the important lessons in this section, besides how to dynamically add and remove elements, is that the jQuery selector has uses far beyond the jQuery function. You’ll definitely want to make sure you practice creating selectors in a wide variety of scenarios so that you are able to create selectors to get references to exactly the page elements you want.

WARNING! The elements you remove using the remove method still appear in the page source. So users with JavaScript can still see the message for people without JavaScript, and those without JavaScript could see the secret embedded in the code in the page. So this is not a technique for protecting content that you want only certain people to see.

ldn-expertdkielyThis post is an excerpt from the online courseware for our ASP.NET 4.0 AJAX and jQuery Using Visual C# 2010 course written by expert Don Kiely.