1 / 40

Lecture 9 Introduction to WPF

Lecture 9 Introduction to WPF. Windows Presentation Foundations. Visual Studio has provided the Windows developers with a couple of choices for creating user interfaces: Windows Forms, which is a basic tool for creating applications that target classic Windows, and

avalon
Download Presentation

Lecture 9 Introduction to WPF

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture 9 Introduction to WPF

  2. Windows Presentation Foundations • Visual Studio has provided the Windows developers with a couple of choices for creating user interfaces: • Windows Forms, which is a basic tool for creating applications that target classic Windows, and • Windows Presentation Foundations (WPF), which provide a wider range of application types and attempts to solve a number of problems with Windows Forms. • WPF is technically platform-independent, and some of its fl exibility can be seen in the fact that a subset of WPF called Silverlight is used to create interactive web applications.

  3. XAML • XAML is a language that uses XML syntax and enables controls to be added to a user interface in a declarative, hierarchical way. You can also have controls that contain other controls, which is essential for both layout and functionality. XAML is XML, which means that as long as the files are fairly small, it is possible to see immediately what it is describing. Take a look at this small example and see if you can tell what it does: • <Window x:Class="Ch15Ex01.MainWindow" • xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" • xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" • Title="MainWindow" Height="350" Width="525"> • <Grid> • <Button Content="Hello World" • HorizontalAlignment="Left" • Margin="220,151,0,0" • VerticalAlignment="Top" • Width="75"/> • </Grid> • </Window> • The XAML in this example creates a window with a single button on it. Both the window and the button display the text "Hello World".

  4. XML Documents A complete set of data in XML is known as an XML document. An XML document could be a physical fi le on your computer or just a string in memory. However, it has to be complete in itself. An XML document is made up of a number of different parts. The most important of these are XML elements, which contain the actual data of the document.

  5. XML Elements • XML elements consist of an opening tag (the name of the element enclosed in angled brackets, such as <myElement>), the data within the element, and a closing tag (the same as the opening tag, but with a forward slash after the opening bracket: </myElement>). • For example, you might define an element to hold the title of a book like this: • <book>Tristram Shandy</book> • Elements can also contain other elements, so you could modify the <book> element to include the author as well as the title by adding two sub-elements: • <book> • <title>Tristram Shandy</title> • <author>Lawrence Sterne</author> • </book> • Or you can use a shorthand syntax, adding the slash of the closing element to the end of the opening element: • <book contents of book element goes here />

  6. XML Attributes • As well as storing data within the body of the element, you can also store data within attributes, which are added within the opening tag of an element. Attributes are in the form • name="value" • where the value of the attribute must be enclosed in either single or double quotes, as in this example: • <book title="Tristram Shandy></book> • or • <book title='Tristram Shandy'></book> • The preceding are both legal, but the following is not: • <book title=Tristram Shandy></book>

  7. XML Declaration In addition to elements and attributes, XML documents can contain a number of constituent parts known as nodes. Elements, the text within elements,and attributes are all nodes of the XML document. One type of node occurs in almost every XML document: the XML declaration. If you include it, it must occur as the first node of the document. The XML declaration is similar in format to an element but has question marks inside the angled brackets. It always has the name xml, and it always has an attribute named version. required.

  8. Versions of XML • Currently there are two possible versions of XML: 1.0 (first edition) and 1.1 (second edition), but perhaps surprisingly Visual Studio does not support the second edition. It should be said that the second edition adds very little to XML that normal use on the Windows platform would demand, and the World Wide Web Consortium (www.w3c.org) encourages you to use the first edition whenever possible. • The simplest possible form of the XML declaration is therefore as follows: • <?xml version="1.0"?> • Optionally, it can also contain the attributes encoding (with a value indicating the character set that should be used to read the document, such as "UTF-16" to indicate that the document uses the 16-bit Unicode character set) and standalone (with the value "yes" or "no" to indicate whether the XML document depends on any other files). However, these attributes are not required.

  9. Structure of an XML Document One of the most important things about XML is that it offers a way of structuring data that is very different from relational databases. Most modern database systems store data in tables that are related to each other through values in individual columns. The tables store data in rows and columns — each row represents a single record, and each column a particular item of data about that record. In contrast, XML data is structured hierarchically, a little like the folders and files in Windows Explorer. If there is more than one element at the top level of the document, the document is not legal XML. OK not OK <?xml version="1.0"?> <books> <book>Tristram Shandy</book> <book>Moby Dick</book> <book>Ulysses</book> </books> <?xml version="1.0"?> <book>Tristram Shandy</book> <book>Moby Dick</book> <book>Ulysses</book>

  10. XML Namespaces • To identify a prefix with a specifi c namespace, use the xmlns:prefix attribute within an element, setting its value to the unique URI that identifi es that namespace. • <?xml version="1.0"?> • <books> • <book xmlns:wrox="http://www.wrox.com"> • <wrox:title>Beginning C#</wrox:title> • <wrox:author>Karli Watson</wrox:author> • </book> • </books> • You can use the wrox: prefi x with the <title> and <author> elements because they are within the <book> element, where the prefi x is defi ned. You can also define a default namespace for an element using the xmlns attribute: • <?xml version="1.0"?> • <books> • <book xmlns="http://www.wrox.com"> • <title>Beginning Visual C#</title> • <author>Karli Watson</author> • <html:img alt="Cover Image" src="begvcsharp.gif" • xmlns:html="http://www.w3.org/1999/xhtml" /> • </book> • </books>

  11. Validating XML Documents Schemas help you validate XML documents by specifing which elements and attributes can be placed in a document and in what order. Schemas are written in an XML-compatible syntax, however they are very complex and difficult to write. Visual Studio supports XML by creating schemas automatically based on the template of a sample XML document.

  12. Sample XML Document <?xmlversion="1.0"encoding="utf-8"?> <Stories> <story> <title>A House in Aungier Street</title> <author> <name>Sheridan Le Fanu</name> <nationality>Irish</nationality> </author> <rating>eerie</rating> </story> <story> <title>The Signalman</title> <author> <name>Charles Dickens</name> <nationality>English</nationality> </author> <rating>atmospheric</rating> </story> <story> <title>The Turn of the Screw</title> <author> <name>Henry James</name> <nationality>American</nationality> </author> <rating>a bit dull</rating> </story> <story> <title>Number 13</title> <author> <name>M.R. James</name> <nationality>English</nationality> </author> <rating>mysterious</rating> </story> </Stories>

  13. Schema Created by Visual Studio <?xmlversion="1.0"encoding="utf-8"?> <xs:schemaattributeFormDefault="unqualified"elementFormDefault="qualified"xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:elementname="Stories"> <xs:complexType> <xs:sequence> <xs:elementmaxOccurs="unbounded"name="story"> <xs:complexType> <xs:sequence> <xs:elementname="title"type="xs:string" /> <xs:elementname="author"> <xs:complexType> <xs:sequence> <xs:elementname="name"type="xs:string" /> <xs:elementname="nationality"type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> <xs:elementname="rating"type="xs:string" /> </xs:sequence> </xs:complexType> </xs:element> </xs:sequence> </xs:complexType> </xs:element> </xs:schema>

  14. Dependency Properties • A dependency property is a property that is registered with the WPF property system in such a way as to allow extended functionality. This extended functionality includes, but is not limited to, automatic property change notifications. Specifically, dependency properties have the following features: • You can use styles to change the values of dependency properties. • You can set the value of a dependency property by using resources or by data binding. • You can change dependency property values in an animation. • You can set dependency properties hierarchically in XAML that is, a value for a dependency property that you set on a parent element can be used to set the default value for the same dependency property of its child elements. • You can configure notifications for property value changes using a well-defi ned coding pattern. • You can configure sets of related properties so that they all update in response to a change to one of them. This is known as coercion. The changed property is said to coerce the values of the other properties. • You can apply metadata to a dependency property to specify other behavior characteristics. For example, you might specify that if a given property changes, then it might be necessary to rearrange the user interface.

  15. Attached Properties An attached property is a property that is made available to each child object of an instance of the class that defines the property. For example the Grid control allows you to define columns and rows for ordering the child controls of the Grid. Each child control can then use the attached properties Column and Row to specify where it belongs in the grid: <Grid HorizontalAlignment="Left" Height="167" VerticalAlignment="Top" Width="290"> <Button Content="Button" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="75" Grid.Column="0" Grid.Row="0" Height="22" /> ... </Grid> Here, the attached property is referred to using the name of the parent element, a period, and the name of the attached property.

  16. Events Events are the means by which the user is afforded functionality by the GUI. For example, when the user clicks a button, that button generates an event indicating what just happened to it. Many of the events you handle are common to most of the controls. This includes events such as LostFocusand MouseEnter, because the events themselves are inherited from base classes such as Control or ContentControl. Other events such as the CalendarOpenedevent of the DatePicker are more specific and only found on specialized controls. Some Common Control Events are given in the table on the next slide.

  17. Routed Events WPF uses events that are called routed events. A standard .NET event is handled by the code that has explicitly subscribed to it and it is sent only to those subscribers. Routed events are different in that they can send the event to all controls in the hierarchy in which the control participates. A routed event can travel up and down the hierarchy of the control on which the event occurred. So, if you right-click a button, the MouseRightButtonDown event will fi rst be sent to the button itself, then to the parent of the control. If this doesn’t handle it, then the event is finally sent to the window. If, on the other hand you don’t want the event to travel further up the hierarchy, then you simply set the RoutedEventArgs property Handled to true, and no additional calls will be made at that point. When an event travels up the control hierarchy like this, it is called a bobbling event. Routed events can also travel in the other direction, that is, from the root element to the control on which the action was performed. This is called a tunneling event and by convention all events like this are prefixedwith the word Preview and always occur before their bobbling counterparts. An example of this is the PreviewMouseRightButtonDown event. Finally, a routed event can behave exactly like a normal .NET event and only be sent to the control on which the action was made.

  18. Routed Commands Routed commands serve much the same purpose as events in that they cause some code to execute. Where Events are bound directly to a single element in the XAML and a handler in the code, Routed Commands can be used when you have code that will be executed to respond to actions that happen in many locations. An example of this is when the content of an application is saved. There is often a menu with a Save command that can be selected, as well as a toolbar button for the same purpose. It is possible to use event handlers to do this, but it would mean implementing the same code in many locations — a command allows you to write the code just once. When you create a command, you must also implement code that can respond to the question, “Should this code be available to the user at the moment?” This means that when a command is associated with a button, that button can ask the command if it can execute and set its state accordingly.

  19. publicpartialclassMainWindow : Window { public MainWindow() { InitializeComponent(); } privatevoid rotated_Button_KeyDown(object sender, KeyEventArgs e) { MessageBox.Show("rotated_Button handler, bubbling up"); } privatevoid Grid_KeyDown(object sender, KeyEventArgs e) { MessageBox.Show("Grid handler, bubbling up"); } privatevoid Window_KeyDown(object sender, KeyEventArgs e) { MessageBox.Show("Window handler, bubbling up"); } privatevoid rotated_Button_PreviewKeyDown(object sender, KeyEventArgs e) { MessageBox.Show("rotated_Button handler, tunneling down"); } privatevoid Grid_PreviewKeyDown(object sender, KeyEventArgs e) { MessageBox.Show("Grid handler, tunneling down"); e.Handled = true; } privatevoid Window_PreviewKeyDown(object sender, KeyEventArgs e) { MessageBox.Show("Window handler, tunneling down"); } } stops the bubbling and/or tunneling

  20. Control Types Content controls, such as the Button control, have a Content property that can be set to any other control. This means that you can determine how the control is displayed, but you can specify only a single control directly in the content. Alternatively, you can specify an Items control, which is a control that allows you to insert multiple controls as content. An example of an Items control is the Grid control. In addition to Content and Items controls, there are a number of other types of controls that don’t allow you to use other controls as their content. One example of this is the Image control, which is used to display an image. Changing that behavior defeats the purpose of the control.

  21. CONTROL LAYOUT • All content layout controls derive from the abstract Panel class. This class simply defines a container that can contain a collection of objects that derive from UIElement. All WPF controls derive from UIElement. You cannot use the Panel class directly for control layout, but you can derive from it if you want to. Alternatively, you can use one of the following layout controls that derive from Panel: • ➤ Canvas — This control enables you to position child controls any way you see fi t. It doesn’t place any restrictions on child control positioning, but nor does it provide any assistance in positioning. • ➤ DockPanel — This control enables you to dock child controls against one of its four edges. The last child control fi lls the remaining space. • ➤ Grid — This control enables fl exible positioning of child controls. You can divide the layout of this control into rows and columns, which enables you to align controls in a grid layout. • ➤ StackPanel — This control positions its child controls in a sequential horizontal or vertical layout. • ➤ WrapPanel — This control positions its child controls in a sequential horizontal or vertical layout as StackPanel, but rather than a single row or column of controls, this control wraps its children into multiple rows or columns according to the space available.

  22. Stack Order When a container control contains multiple child controls, they are drawn in a specific stack order. If a control is higher up the stack, then it will be the control that you see in the overlap area. Controls lower down may be partially or completely hidden by controls above them. This also affects hit testing when you click on a window with the mouse. The target control will always be the one that is uppermost in the stack when considering overlapping controls. The stack order of controls is determined by the order in which they appear in the list of children for a container. The first child in a container is placed on the lowest layer in the stack, and the last child on the topmost layer. The children between the first and last child are placed on increasingly higher layers.

  23. Alignment, Margins, Padding, and Dimensions HorizontalAlignmentcan be set to Left, Right, Center, or Stretch. Left and Right tend to position controls to the left or right edges of the container, Center positions controls in the middle, and Stretch changes the width of the control so that its edges reach to the sides of the container. VerticalAlignment is similar, and has the values Top, Bottom, Center, or Stretch. Margin is used to position controls relative to the edges of a window. Paddingis used similarly, but spaces out the content of a control from its edges. This is particularly useful for Border.

  24. Border The Border control holds a single child that will be sized to completely fill the Border control. You can use the Margin and Padding properties to position the Border within its container, and the content of the Border within the edges of the Border. You can also set the Background property of a Border so that it is visible.

  25. Canvas • The Canvas control provides complete freedom over control positioning. Another thing about Canvas is that the HorizontalAligment and VerticalAlignment properties used with a child element will have no effect whatsoever over the positioning of those elements. You can use the Canvas.Left, Canvas.Top, Canvas.Right, and Canvas.Bottom attached properties that the Canvas class exposes: • <Canvas…> • <Button Canvas.Top="10" Canvas.Left="10"…>Button1</Button> • </Canvas> • The preceding code positions a Button so that its top edge is 10 pixels from the top edge of the Canvas, and its left edge is 10 pixels from the left edge of the Canvas. Note that the Top and Left properties take precedence over Bottom and Right. For example, if you specify both Top and Bottom, then the Bottom property is ignored.

  26. One Rectangle is positioned relative to the top-left corner, and one is positioned relative to the bottom-right corner. As you resize the window, these relative positions are maintained. You can also see the importance of the stacking order of the Rectangle controls. The bottom-right Rectangle is higher up in the stacking order, so when they overlap this is the control that you see.

More Related