This tutorial has been designed for all those readers who want to learn WPF and to apply it instantaneously in different type of applications.

Size: px
Start display at page:

Download "This tutorial has been designed for all those readers who want to learn WPF and to apply it instantaneously in different type of applications."

Transcription

1

2 About the Tutorial WPF stands for Windows Presentation Foundation. It is a powerful framework for building Windows applications. This tutorial explains the features that you need to understand to build WPF applications and how it brings a fundamental change in Windows applications. Audience This tutorial has been designed for all those readers who want to learn WPF and to apply it instantaneously in different type of applications. Prerequisites Before proceeding with this tutorial, you should have a basic understanding of XML, Web Technologies and HTML. Copyright & Disclaimer Copyright 2015 by Tutorials Point (I) Pvt. Ltd. All the content and graphics published in this e-book are the property of Tutorials Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish any contents or a part of contents of this e-book in any manner without written consent of the publisher. We strive to update the contents of our website and tutorials as timely and as precisely as possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our website or its contents including this tutorial. If you discover any errors on our website or in this tutorial, please notify us at contact@tutorialspoint.com i

3 Table of Contents About the Tutorial... i Audience... i Prerequisites... i Copyright & Disclaimer... i Table of Contents... ii 1. WPF OVERVIEW... 1 WPF Architecture... 1 WPF Advantages... 2 WPF Features WPF ENVIRONMENT SETUP... 3 Installation WPF HELLO WORLD WPF XAML OVERVIEW Basic Syntax Why XAML in WPF WPF ELEMENTS TREE Logical Tree Structure Visual Tree Structure WPF DEPENDENCY PROPERTIES Why We Need Dependency Properties Custom Dependency Properties WPF ROUTED EVENTS Direct Event ii

4 Bubbling Event Tunnel Event Custom Routed Events WPF CONTROLS BUTTON CALENDAR CHECKBOX COMBOBOX CONTEXTMENU DATAGRID DATEPICKER DIALOG BOX GRIDVIEW IMAGE LABEL LISTBOX MENU PASSWORDBOX POPUP PROGRESSBAR RADIOBUTTON iii

5 26. SCROLLVIEWER SLIDER TEXTBLOCK TOGGLEBUTTON TOOLTIP WINDOW THIRD-PARTY CONTROLS WPF LAYOUTS Stack Panel Wrap Panel Dock Panel Canvas Panel Grid Panel NESTING OF LAYOUT WPF INPUT Mouse Keyboard ContextMenu or RoutedCommands Multi Touch WPF COMMAND LINE WPF DATA BINDING One-Way Data Binding Two-Way Data Binding iv

6 38. WPF RESOURCES Resource Scope Resource Dictionaries WPF TEMPLATES Control Template Data Template WPF STYLES Control Level Layout Level Window Level Application Level WPF TRIGGERS Property Triggers Data Triggers Event Triggers WPF DEBUGGING Debugging in C# Debugging in XAML UI Debugging Tools for XAML WPF CUSTOM CONTROLS User Control Custom Controls WPF EXCEPTION HANDLING Syntax Hierarchy v

7 45. WPF LOCALIZATION WPF INTERACTION Behaviors Drag and Drop WPF 2D GRAPHICS Shapes and Drawing WPF 3D GRAPHICS WPF MULTIMEDIA Speech Synthesizer vi

8 1. WPF OVERVIEW WPF WPF stands for Windows Presentation Foundation. It is a powerful framework for building Windows applications. This tutorial explains the features that you need to understand to build WPF applications and how it brings a fundamental change in Windows applications. WPF was first introduces in.net framework 3.0 version, and then so many other features were added in the subsequent.net framework versions. WPF Architecture Before WPF, the other user interface frameworks offered by Microsoft such as MFC and Windows forms, were just wrappers around User32 and GDI32 DLLs, but WPF makes only minimal use of User32. So, WPF is more than just a wrapper. It is a part of the.net framework. It contains a mixture of managed and unmanaged code. The major components of WPF architecture are as shown in the figure below. The most important code part of WPF are: Presentation Framework Presentation Core Milcore Presentation Framework Presentation Core CLR Milcore User32 DirectX Kernel The presentation framework and the presentation core have been written in managed code. Milcore is a part of unmanaged code which allows tight integration with DirectX 1

9 (responsible for display and rendering). CLR makes the development process more productive by offering many features such as memory management, error handling, etc. WPF Advantages In the earlier GUI frameworks, there was no real separation between how an application looks like and how it behaved. Both GUI and behavior was created in the same language, e.g. C# or VB.Net which would require more effort from the developer to implement both UI and behavior associated with it. In WPF, UI elements are designed in XAML while behaviors can be implemented in procedural languages such C# and VB.Net. So it very easy to separate behavior from the designer code. With XAML, the programmers can work in parallel with the designers. The separation between a GUI and its behavior can allow us to easily change the look of a control by using styles and templates. WPF Features WPF is a powerful framework to create Windows application. It supports many great features, some of which have been listed below: Feature Description Control inside a Control Allows to define a control inside another control as a content. Data binding Mechanism to display and interact with data between UI elements and data object on user interface. Media services Provides an integrated system for building user interfaces with common media elements like images, audio, and video. Templates In WPF you can define the look of an element directly with a Template Animations Building interactivity and movement on user Interface Alternative input Supports multi-touch input on Windows 7 and above. Direct3D Allows to display more complex graphics and custom themes 2

10 2. WPF ENVIRONMENT SETUP WPF Microsoft provides two important tools for WPF application development. Visual Studio Expression Blend Both the tools can create WPF projects, but the fact is that Visual Studio is used more by developers, while Blend is used more often by designers. For this tutorial, we will mostly be using Visual Studio. Installation Microsoft provides a free version of Visual Studio which can be downloaded from Download the files and follow the steps given below to set up WPF application development environment on your system. 1. After the download is complete, run the installer. The following dialog will be displayed. 3

11 2. Click the Install button and it will start the installation process. 4

12 3. Once the installation process is completed successfully, you will get to see the following dialog box. 4. Close this dialog box and restart your computer if required. 5. Now open Visual Studio from the Start Menu which will open the following dialog box. 5

13 6. Once all is done, you will see the main window of Visual Studio. You are now ready to build your first WPF application. 6

14 3. WPF HELLO WORLD WPF In this chapter, we will develop a simple Hello World WPF application. So let s start the simple implementation by following the steps given below. 1. Click on File > New > Project menu option. 7

15 2. The following dialog box will be displayed. 3. Under Templates, select Visual C# and in the middle panel, select WPF Application. 4. Give the project a name. Type HelloWorld in the name field and click the OK button. 5. By default, two files are created, one is the XAML file (mainwindow.xaml) and the other one is the CS file (mainwindow.cs) 6. On mainwindow.xaml, you will see two sub-windows, one is the design window and the other one is the source (XAML) window. 7. In WPF application, there are two ways to design an UI for your application. One is to simply drag and drop UI elements from the toolbox to the Design Window. The second way is to design your UI by writing XAML tags for UI elements. Visual Studio handles XAML tags when drag and drop feature is used for UI designing. 8. In mainwindow.xaml file, the following XAML tags are written by default. <Window x:class="helloworld.mainwindow" xmlns=" xmlns:x=" Title="MainWindow" Height="350" Width="604"> <Grid> 8

16 </Grid> </Window> 9. By default, a Grid is set as the first element after page. 10. Let s go to the toolbox and drag a TextBlock to the design window. 11. You will see the TextBlock on the design window. 9

17 12. When you look at the source window, you will see that Visual Studio has generated the XAML code of the TextBlock for you. 13. Let s change the Text property of TextBlock in XAML code from TextBlock to Hello World. <Window x:class="helloworld.mainwindow" <Grid> </Grid> </Window> xmlns=" xmlns:x=" Title="MainWindow" Height="350" Width="604"> <TextBlock x:name="textblock" HorizontalAlignment="Left" Margin="235,143,0,0" TextWrapping="Wrap" Text="Hello World!" VerticalAlignment="Top" Height="44" Width="102"/> 14. Now, you will see the change on the Design Window as well. 10

18 When the above code is compiled and executed, you will see the following window. Congratulations! You have designed and created your first WPF application. 11

19 4. WPF XAML OVERVIEW WPF One of the first things you will encounter while working with WPF is XAML. XAML stands for Extensible Application Markup Language. It s a simple and declarative language based on XML. In XAML, it very easy to create, initialize, and set properties of objects with hierarchical relations. It is mainly used for designing GUIs, however it can be used for other purposes as well, e.g., to declare workflow in Workflow Foundation. Basic Syntax When you create your new WPF project, you will encounter some of the XAML code by default in MainWindow.xaml as shown below. <Window x:class="resources.mainwindow" <Grid> xmlns=" xmlns:x=" Title="MainWindow" Height="350" Width="525"> </Grid> </Window> The above XAML file contains different kinds of information. The following table briefly explains the role of each information. <Window Information x:class="resources.mainwindow" xmlns=" winfx/2006/xaml/presentation" xmlns:x=" m/winfx/2006/xaml" Description It is the opening object element or container of the root. It is a partial class declaration which connects the markup to the partial class code defined behind. Maps the default XAML namespace for WPF client/framework. XAML namespace for XAML language which maps it to x: prefix > End of object element of the root <Grid> It is starting and closing tags of an empty grid </Grid> object. </Window> Closing the object element 12

20 The syntax rules for XAML is almost similar to XML. If you look at an XAML document, then you will notice that it is actually a valid XML file, but an XML file is not necessarily an XAML file. It is because in XML, the value of the attributes must be a string while in XAML, it can be a different object which is known as Property element syntax. The syntax of an Object element starts with a left angle bracket (<) followed by the name of an object, e.g. Button. Define some Properties and attributes of that object element. The Object element must be closed by a forward slash (/) followed immediately by a right angle bracket (>). Example of simple object with no child element: <Button/> Example of object element with some attributes: <Button Content="Click Me" Height="30" Width="60"/> Example of an alternate syntax do define properties (Property element syntax): <Button </Button> <Button.Content>Click Me</Button.Content> <Button.Height>30</Button.Height> <Button.Width>60</Button.Width> Example of Object with Child Element: StackPanel contains Textblock as child element <StackPanel Orientation="Horizontal"> </StackPanel> <TextBlock Text="Hello"/> Why XAML in WPF XAML is not only the most widely known feature of WPF, but it's also one of the most misunderstood features. If you have exposure to WPF, then you must have heard of XAML; but take a note of the following two less known facts about XAML: 13

21 WPF doesn't need XAML XAML doesn't need WPF They are in fact separable pieces of technology. To understand how that can be, let's look at a simple example in which a button is created with some properties in XAML. <Window x:class="wpfxamloverview.mainwindow" xmlns=" xmlns:x=" Title="MainWindow" Height="350" Width="604"> <StackPanel> <Button x:name="button" </StackPanel> </Window> Content="Click Me" HorizontalAlignment="Left" Margin="150" VerticalAlignment="Top" Width="75"/> In case you choose not to use XAML in WPF, then you can achieve the same GUI result with procedural language as well. Let s have a look at the same example, but this time, we will create a button in C#. using System.Windows; using System.Windows.Controls; namespace WPFXAMLOverview /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window public MainWindow() InitializeComponent(); // Create the StackPanel StackPanel stackpanel = new StackPanel(); 14

22 this.content = stackpanel; // Create the Button Button button = new Button(); button.content = "Click Me"; button.horizontalalignment = HorizontalAlignment.Left; button.margin = new Thickness(150); button.verticalalignment = VerticalAlignment.Top; button.width = 75; stackpanel.children.add(button); When you compile and execute either the XAML code or the C# code, you will see the same output as shown below. From the above example, it is clear that what you can do in XAML to create, initialize, and set properties of objects, the same tasks can also be done using code. XAML is just another simple and easy way to design UI elements. With XAML, it doesn t mean that what you can do to design UI elements is the only way. You can either declare the objects in XAML or define them using code. 15

23 XAML is optional, but despite this, it is at the heart of WPF design. The goal of XAML is to enable visual designers to create user interface elements directly. WPF aims to make it possible to control all visual aspects of the user interface from mark-up. 16

24 5. WPF ELEMENTS TREE WPF There are many technologies where the elements and components are ordered in a tree structure so that the programmers can easily handle the object and change the behavior of an application. Windows Presentation Foundation (WPF) has a comprehensive tree structure in the form of objects. In WPF, there are two ways that a complete object tree is conceptualized: Logical Tree Structure Visual Tree Structure With the help of these tree structures, you can easily create and identify the relationship between UI elements. Mostly, WPF developers and designers either use procedural language to create an application or design the UI part of the application in XAML keeping in mind the object tree structure. Logical Tree Structure In WPF applications, the structure of the UI elements in XAML represents the logical tree structure. In XAML, the basic elements of UI are declared by the developer. The logical tree in WPF defines the following: Dependency properties Static and dynamic resources Binding the elements on its name etc. Let s have a look at the following example in which a button and a list box are created. <Window x:class="wpfelementstree.mainwindow" xmlns=" xmlns:x=" Title="MainWindow" Height="350" Width="604"> <StackPanel> <Button x:name="button" Height="30" Width="70" Content="OK" Margin="20"/> <ListBox x:name="listbox" Height="100" Width="100" Margin="20"> <ListBoxItem Content="Item 1"/> <ListBoxItem Content="Item 2"/> <ListBoxItem Content="Item 3"/> </ListBox> </StackPanel> </Window> 17

25 If you look at the XAML code, you will observe a tree structure, i.e. the root node is the Window and inside the root node, there is only one child, that is StackPanel. But StackPanel contains two child elements, button and list box. List box has three more child list box items. Visual Tree Structure In WPF, the concept of the visual tree describes the structure of visual objects, as represented by the Visual Base Class. It signifies all the UI elements which are rendered to the output screen. When a programmer wants to create a template for a particular control, he is actually rendering the visual tree of that control. The visual tree is also very useful for those who want to draw lower level controls for performance and optimization reasons. In WPF applications, visual tree is used for; Rendering the visual objects. Rendering the layouts. The routed events mostly travel along the visual tree, not the logical tree. To see the visual tree of the above simple application which contains a button and a list box, let s compile and execute the XAML code and you will see the following window. When the application is running, you can see the visual tree of the running application in Live Visual Tree window which shows the complete hierarchy of this application, as shown below. 18

26 The visual tree is typically a superset of the logical tree. You can see here that all the logical elements are also present in the visual tree. So these two trees are really just two different views of the same set of objects that make up the UI. The logical tree leaves out a lot of detail enabling you to focus on the core structure of the user interface and to ignore the details of exactly how it has been presented. The logical tree is what you use to create the basic structure of the user interface. The visual tree will be of interest if you're focusing on the presentation. For example, if you wish to customize the appearance of any UI element, you will need to use the visual tree. 19

27 6. WPF DEPENDENCY PROPERTIES WPF In WPF applications, dependency property is a specific type of property which extends the CLR property. It takes the advantage of specific functionalities available in the WPF property system. A class which defines a dependency property must be inherited from the DependencyObject class. Many of the UI controls class which are used in XAML are derived from the DependencyObject class and they support dependency properties, e.g. Button class supports the IsMouseOver dependency property. The following XAML code creates a button with some properties. <Window x:class="wpfdependencyproperty.mainwindow" <Grid> </Grid> </Window> xmlns=" xmlns:x=" xmlns:local="clr-namespace:wpfdependencyproperty" Title="MainWindow" Height="350" Width="604"> <Button Height="40" Width="175" Margin="10" Content="Dependency Property"> <Button.Style> <Style TargetType="x:Type Button"> </Style> </Button.Style> </Button> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Foreground" Value="Red"/> </Trigger> </Style.Triggers> The x:type markup extension in XAML has a similar functionality like typeof() in C#. It is used when attributes are specified which take the type of the object such as <Style TargetType="x:Type Button"> 20

28 When the above code is compiled and executed, you would get the following MainWindow. When the mouse is over the button, it will change the foreground color of a button. When the mouse leaves the button, it changes back to its original color. Why We Need Dependency Properties Dependency property gives you all kinds of benefits when you use it in your application. Dependency Property can used over a CLR property in the following scenarios; If you want to set the style If you want data binding If you want to set with a resource (a static or a dynamic resource) If you want to support animation Basically, Dependency Properties offer a lot of functionalities that you won t get by using a CLR property. The main difference between dependency properties and other CLR properties are listed below: CLR properties can directly read/write from the private member of a class by using getter and setter. In contrast, dependency properties are not stored in local object. Dependency properties are stored in a dictionary of key/value pairs which is provided by the DependencyObject class. It also saves a lot of memory because it stores the property when changed. It can be bound in XAML as well. 21

29 Custom Dependency Properties In.NET framework, custom dependency properties can also be defined. Follow the steps given below to define custom dependency property in C#. Declare and register your dependency property with system call register. Provide the setter and getter for the property. Define a static handler which will handle any changes that occur globally Define an instance handler which will handle any changes that occur to that particular instance. The following C# code defines a dependency property to set the SetText property of the user control. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WpfApplication3 /// <summary> /// Interaction logic for UserControl1.xaml /// </summary> public partial class UserControl1 : UserControl public UserControl1() InitializeComponent(); 22

30 public static readonly DependencyProperty SetTextProperty = DependencyProperty.Register("SetText", typeof(string), typeof(usercontrol1), new PropertyMetadata("", new PropertyChangedCallback(OnSetTextChanged))); public string SetText get return (string)getvalue(settextproperty); set SetValue(SetTextProperty, value); private static void OnSetTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) UserControl1 UserControl1Control = d as UserControl1; UserControl1Control.OnSetTextChanged(e); private void OnSetTextChanged(DependencyPropertyChangedEventArgs e) tbtest.text = e.newvalue.tostring(); Here is the XAML file in which the TextBlock is defined as a user control and the Text property will be assigned to it by the SetText dependency property. The following XAML code creates a user control and initializes its SetText dependency property. <Window x:class="wpfapplication3.mainwindow" <Grid> </Grid> </Window> xmlns=" xmlns:x=" xmlns:views="clr-namespace:wpfapplication3" Title="MainWindow" Height="350" Width="604"> <views:usercontrol1 SetText="Hellow World"/> 23

31 Let's run this application. You can immediately observe that in our MainWindow, the dependency property for user control has been successfully used as a Text. 24

32 7. WPF ROUTED EVENTS WPF A routed event is a type of event that can invoke handlers on multiple listeners in an element tree rather than just the object that raised the event. It is basically a CLR event that is supported by an instance of the Routed Event class. It is registered with the WPF event system. RoutedEvents have three main routing strategies which are as follows; Direct Event Bubbling Event Tunnel Event Direct Event A direct event is similar to events in Windows forums which are raised by the element in which the event is originated. Unlike a standard CLR event, direct routed events support class handling and they can be used in Event Setters and Event Triggers within your style of your Custom Control. A good example of a direct event would be the MouseEnter event. Bubbling Event A bubbling event begins with the element where the event is originated. Then it travels up the visual tree to the topmost element in the visual tree. So, in WPF, the topmost element is most likely a window. Tunnel Event Event handlers on the element tree root are invoked and then the event travels down the visual tree to all the children nodes until it reaches the element in which the event originated. The difference between a bubbling and a tunneling event is that a tunneling event will always start with a preview. In a WPF application, events are often implemented as a tunneling/bubbling pair. So, you'll have a preview MouseDown and then a MouseDown event. Given below is a simple example of a Routed event in which a button and three text blocks are created with some properties and events. <Window x:class="wpfroutedevents.mainwindow" xmlns=" xmlns:x=" Title="MainWindow" Height="450" Width="604" 25

33 <Grid> TextBlock 1" /> TextBlock 2" /> TextBlock 3" /> </Grid> </Window> ButtonBase.Click ="Window_Click" > <StackPanel Margin="20" ButtonBase.Click="StackPanel_Click"> <StackPanel Margin="10"> <TextBlock Name="txt1" FontSize="18" Margin="5" Text="This is a <TextBlock Name="txt2" FontSize="18" Margin="5" Text="This is a <TextBlock Name="txt3" FontSize="18" Margin="5" Text="This is a </StackPanel> <Button Margin="10" Content="Click me" </StackPanel> Click="Button_Click" Width="80"/> Here is the C# code for the Click events implementation for Button, StackPanel, and Window. using System.Windows; namespace WPFRoutedEvents /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window public MainWindow() InitializeComponent(); private void Button_Click(object sender, RoutedEventArgs e) txt1.text = "Button is Clicked"; 26

34 private void StackPanel_Click(object sender, RoutedEventArgs e) txt2.text = "Click event is bubbled to Stack Panel"; private void Window_Click(object sender, RoutedEventArgs e) txt3.text = "Click event is bubbled to Window"; When you compile and execute the above code, it will produce the following window: 27

35 When you click on the button, the text blocks will get updated, as shown below. If you want to stop the routed event at any particular level, then you will need to set the e.handled = true; Let s change the StackPanel_Click event as shown below: private void StackPanel_Click(object sender, RoutedEventArgs e) txt2.text = "Click event is bubbled to Stack Panel"; e.handled = true; When you click on the button, you will observe that the click event will not be routed to the window and will stop at the stackpanel and the 3 rd text block will not be updated. o 28

36 Custom Routed Events In.NET framework, custom routed event can also be defined. You need to follow the steps given below to define a custom routed event in C#. Declare and register your routed event with system call RegisterRoutedEvent. Specify the Routing Strategy, i.e. Bubble, Tunnel, or Direct. Provide the event handler. Let s take an example to understand more about custom routed events. Follow the steps given below: 1. Create a new WPF project with WPFCustomRoutedEvent 2. Right click on your solution and select Add > New Item The following dialog will open, now select Custom Control (WPF) and name it MyCustomControl. 4. Click the Add button and you will see that two new files (Themes/Generic.xaml and MyCustomControl.cs) will be added in your solution. The following XAML code sets the style for the custom control in Generic.xaml file. <ResourceDictionary xmlns=" xmlns:x=" xmlns:local="clr-namespace:wpfcustomroutedevent"> 29

37 <Style TargetType="x:Type local:mycustomcontrol"> <Setter Property="Margin" Value="50"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="x:Type local:mycustomcontrol"> <Border Background="TemplateBinding Background" BorderBrush="TemplateBinding BorderBrush" BorderThickness="TemplateBinding BorderThickness"> <Button x:name="part_button" Content="Click Me" /> </Border> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> Given below is the C# code for the MyCustomControl class which inherits from the Control class in which a custom routed event Click is created for the custom control. using System.Windows; using System.Windows.Controls; namespace WPFCustomRoutedEvent public class MyCustomControl : Control static MyCustomControl() DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl))); public override void OnApplyTemplate() base.onapplytemplate(); //demo purpose only, check for previous instances and remove the handler first var button = GetTemplateChild("PART_Button") as Button; 30

38 if (button!= null) button.click += Button_Click; void Button_Click(object sender, RoutedEventArgs e) RaiseClickEvent(); public static readonly RoutedEvent ClickEvent = EventManager.RegisterRoutedEvent("Click", RoutingStrategy.Bubble, typeof(routedeventhandler), typeof(mycustomcontrol)); public event RoutedEventHandler Click add AddHandler(ClickEvent, value); remove RemoveHandler(ClickEvent, value); protected virtual void RaiseClickEvent() RoutedEventArgs args = new RoutedEventArgs(MyCustomControl.ClickEvent); RaiseEvent(args); Here is the custom routed event implementation in C# which will display a message box when the user clicks it. using System.Windows; namespace WPFCustomRoutedEvent // <summary> // Interaction logic for MainWindow.xaml 31

39 // </summary> public partial class MainWindow : Window public MainWindow() InitializeComponent(); private void MyCustomControl_Click(object sender, RoutedEventArgs e) MessageBox.Show("It is the custom routed event of your custom control"); Here is the implementation in MainWindow.xaml to add the custom control with a routed event Click. <Window x:class="wpfcustomroutedevent.mainwindow" <Grid> </Grid> </Window> xmlns=" xmlns:x=" xmlns:local="clr-namespace:wpfcustomroutedevent" Title="MainWindow" Height="350" Width="604"> <local:mycustomcontrol Click="MyCustomControl_Click"/> When the above code is compiled and executed, it will produce the following window which contains a custom control. 32

40 When you click on the custom control, it will produce the following message. 33

41 8. WPF CONTROLS WPF Windows Presentation Foundation (WPF) allows developers to easily build and create visually enriched UI based applications. The classical UI elements or controls in other UI frameworks are also enhanced in WPF applications. All of the standard WPF controls can be found in the Toolbox which is a part of the System.Windows.Controls. These controls can also be created in XAML markup language. The complete inheritance hierarchy of WPF controls are as follows: 34

42 The following table contains a list of controls which we will discuss in the subsequent chapters. Sr. No. Controls & Description 1 Button A control that responds to user input 2 Calendar Represents a control that enables a user to select a date by using a visual calendar display. 3 CheckBox A control that a user can select or clear. 4 ComboBox A drop-down list of items a user can select from. 5 ContextMenu Gets or sets the context menu element that should appear whenever the context menu is requested through user interface (UI) from within this element. 6 DataGrid Represents a control that displays data in a customizable grid. 7 DatePicker A control that lets a user select a date. 8 Dialogs An application may also display additional windows to help the user gather or display important information. 9 GridView A control that presents a collection of items in rows and columns that can scroll horizontally. 10 Image A control that presents an image. 11 Label Displays text on a form. Provides support for access keys. 12 ListBox A control that presents an inline list of items that the user can select from. 13 Menus Represents a Windows menu control that enables you to hierarchically organize elements associated with commands and event handlers. 14 PasswordBox A control for entering passwords. 15 Popup Displays content on top of existing content, within the bounds of the application window. 16 ProgressBar A control that indicates progress by displaying a bar. 35

43 17 RadioButton A control that allows a user to select a single option from a group of options. 18 ScrollViewer A container control that lets the user pan and zoom its content. 19 Slider A control that lets the user select from a range of values by moving a Thumb control along a track. 20 TextBlock A control that displays text. 21 ToggleButton A button that can be toggled between 2 states. 22 ToolTip A pop-up window that displays information for an element. 23 Window The root window which provides minimize/maximize option, Title bar, border and close button 24 3 rd Party Controls Use third-party controls in your WPF applications. We will discuss all these controls one by one with their implementation. 36

44 9. BUTTON WPF The Button class represents the most basic type of button control. The hierarchical inheritance of Button class is as follows: 37

45 Commonly Used Properties of Button Class Sr. No. Property & Description 1 Background Gets or sets a brush that provides the background of the control. (Inherited from Control) 2 BorderBrush Gets or sets a brush that describes the border fill of a control. (Inherited from Control) 3 BorderThickness Gets or sets the border thickness of a control. (Inherited from Control) 4 Content Gets or sets the content of a ContentControl. (Inherited from ContentControl) 5 ClickMode Gets or sets a value that indicates when the Click event occurs, in terms of device behavior. (Inherited from ButtonBase) 6 ContentTemplate Gets or sets the data template that is used to display the content of the ContentControl. (Inherited from ContentControl) 7 FontFamily Gets or sets the font used to display text in the control. (Inherited from Control) 8 FontSize Gets or sets the size of the text in this control. (Inherited from Control) 9 FontStyle Gets or sets the style in which the text is rendered. (Inherited from Control) 38

46 10 FontWeight Gets or sets the thickness of the specified font. (Inherited from Control) 11 Foreground Gets or sets a brush that describes the foreground color. (Inherited from Control) 12 Height Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement) 13 HorizontalAlignment Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement) 14 IsEnabled Gets or sets a value indicating whether the user can interact with the control. (Inherited from Control) 15 IsPressed Gets a value that indicates whether a ButtonBase is currently in a pressed state. (Inherited from ButtonBase) 16 Margin Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement) 17 Name Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAML-declared object by this name. (Inherited from FrameworkElement) 18 Opacity Gets or sets the degree of the object's opacity. (Inherited from UIElement) 19 Resources Gets the locally defined resource dictionary. In XAML, you can establish resource items as child object elements of a frameworkelement.resources property element, through XAML implicit collection syntax. (Inherited from FrameworkElement) 39

47 20 Style Gets or sets an instance Style that is applied for this object during layout and rendering. (Inherited from FrameworkElement) 21 Template Gets or sets a control template. The control template defines the visual appearance of a control in UI, and is defined in XAML markup. (Inherited from Control) 22 VerticalAlignment Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement) 23 Visibility Gets or sets the visibility of a UIElement. A UIElement that is not visible is not rendered and does not communicate its desired size to layout. (Inherited from UIElement) 24 Width Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement) Commonly Used Methods of Button Class Sr. No. Method & Description 1 ClearValue Clears the local value of a dependency property. (Inherited from DependencyObject) 2 FindName Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement) 40

48 3 OnApplyTemplate Invoked whenever application code or internal processes (such as a rebuilding layout pass) call ApplyTemplate. In simplest terms, this means the method is called just before a UI element displays in your app. Override this method to influence the default post-template logic of a class. (Inherited from FrameworkElement) 4 OnContentChanged Invoked when the value of the Content property changes. (Inherited from ContentControl) 5 OnDragEnter Called before the DragEnter event occurs. (Inherited from Control) 6 OnDragLeave Called before the DragLeave event occurs. (Inherited from Control) 7 OnDragOver Called before the DragOver event occurs. (Inherited from Control) 8 OnDrop Called before the Drop event occurs. (Inherited from Control) 9 OnGotFocus Called before the GotFocus event occurs. (Inherited from Control) 10 OnKeyDown Called before the KeyDown event occurs. (Inherited from Control) 41

49 11 OnKeyUp Called before the KeyUp event occurs. (Inherited from Control) 12 OnLostFocus Called before the LostFocus event occurs. (Inherited from Control) 13 SetBinding Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement) Commonly Used Events of Button Class Sr. No Event & Description Click Occurs when a button control is clicked. (Inherited from ButtonBase) DataContextChanged Occurs when the value of the FrameworkElement.DataContext property changes. (Inherited from FrameworkElement) DragEnter Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement) DragLeave Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement) DragOver Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement) DragStarting Occurs when a drag operation is initiated. (Inherited from UIElement) GotFocus Occurs when a UIElement receives focus. (Inherited from UIElement) Holding Occurs when an otherwise unhandled Hold interaction occurs over the hit test area of this element. (Inherited from UIElement) IsEnabledChanged Occurs when the IsEnabled property changes. (Inherited from Control) KeyDown Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement) 42

50 11 12 KeyUp Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement) LostFocus Occurs when a UIElement loses focus. (Inherited from UIElement) 13 SizeChanged Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement. (Inherited from FrameworkElement) Example Let s take a simple example to understand the concepts better. Follow the steps given below: 1. Open Visual Studio and then Click File > New > Project menu option. 2. In the New Project dialog box, in the Templates pane, click on Visual C# and in middle pane, select WPF Application. 3. In the Name box, type WPFButtonControl, and then click OK. 4. A new WPF project is created. 5. Drag a Button control from the Toolbox to the WPF design window. 6. Now click the button and go to the Properties window and set the following properties of the button. Property Value Content Click Me Margin 200 Height 20 Width If you look at the XAML window, you will see the following code which is generated by Visual Studio. <Window x:class="wpfbuttoncontrol.mainwindow" xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfbuttoncontrol" mc:ignorable="d" 43

51 <Grid> Title="MainWindow" Height="350" Width="525"> <Button x:name="button" Content="Click Me" HorizontalAlignment="Left" Margin="194,150,0,0" VerticalAlignment="Top" Width="75"/> </Grid> </Window> 8. Let s now go to the design window and double-click on the button which will open the MainWindow.xaml.cs file. 9. We will write the following C# code to display a message when the user clicks the button. using System.Windows; namespace WPFButtonControl /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window public MainWindow() InitializeComponent(); private void button_click(object sender, RoutedEventArgs e) MessageBox.Show("You have clicked the button"); When you compile and execute the above code, it will produce the following output: 44

52 When you click the button, it will display the following message: We recommend that you execute the above example code and experiment with some other properties and events. 45

53 10. CALENDAR WPF Calendar is a control that enables a user to select a date by using a visual calendar display. It provides some basic navigation using either the mouse or keyboard. The hierarchical inheritance of Calendar class is as follows: Commonly Used Properties of Calendar Class Sr. No. Properties & Description 1 BlackoutDates Gets a collection of dates that are marked as not selectable. 2 CalendarButtonStyle Gets or sets the Style associated with the control's internal CalendarButton object. 3 CalendarDayButtonStyle Gets or sets the Style associated with the control's internal CalendarDayButton object. 46

54 4 CalendarItemStyle Gets or sets the Style associated with the control's internal CalendarItem object. 5 DisplayDate Gets or sets the date to display. 6 DisplayDateEnd Gets or sets the last date in the date range that is available in the calendar. 7 DisplayDateStart Gets or sets the first date that is available in the calendar. 8 DisplayMode Gets or sets a value that indicates whether the calendar displays a month, year, or decade. 9 FirstDayOfWeek Gets or sets the day that is considered the beginning of the week. 10 IsTodayHighlighted Gets or sets a value that indicates whether the current date is highlighted. 11 SelectedDate Gets or sets the currently selected date. 12 SelectedDates Gets a collection of selected dates. 13 SelectionMode Gets or sets a value that indicates what kind of selections are allowed. Commonly Used Methods of Calendar Class Sr. No. Method & Description 1 OnApplyTemplate Builds the visual tree for the Calendar control when a new template is applied. (Overrides FrameworkElement.OnApplyTemplate().) 47

55 2 ToString Provides a text representation of the selected date. (Overrides Control.ToString().) Commonly Used Events of Calendar Class Sr. No. Events & Description 1 DisplayDateChanged Occurs when the DisplayDate property is changed. 2 DisplayModeChanged Occurs when the DisplayMode property is changed. 3 SelectedDatesChanged Occurs when the collection returned by the SelectedDates property is changed. 4 SelectionModeChanged Occurs when the SelectionMode changes. Example 1. Let s create a new WPF project with WPFCalenderControl name. 2. Drag the calendar control from a toolbox and change the background color in the properties window. 3. Now switch to XAML window in which you will see the XAML tags for calendar and its background. 4. Add some more properties to set the blackouts dates and selection event, as shown in the following XAML code. <Window x:class="wpfcalendercontrol.mainwindow" <Grid> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfcalendercontrol" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <Calendar Margin="20" SelectionMode="MultipleRange" 48

56 IsTodayHighlighted="false" DisplayDate="1/1/2015" DisplayDateEnd="1/31/2015" SelectedDatesChanged="Calendar_SelectedDatesChanged" xmlns:sys="clr-namespace:system;assembly=mscorlib"> <Calendar.BlackoutDates> <CalendarDateRange Start="1/2/2015" End="1/4/2015"/> <CalendarDateRange Start="1/9/2015" End="1/9/2015"/> <CalendarDateRange Start="1/16/2015" End="1/16/2015"/> <CalendarDateRange Start="1/23/2015" End="1/25/2015"/> <CalendarDateRange Start="1/30/2015" End="1/30/2015"/> </Calendar.BlackoutDates> <Calendar.SelectedDates> <sys:datetime>1/5/2015</sys:datetime> <sys:datetime>1/12/2015</sys:datetime> <sys:datetime>1/14/2015</sys:datetime> <sys:datetime>1/13/2015</sys:datetime> <sys:datetime>1/15/2015</sys:datetime> <sys:datetime>1/27/2015</sys:datetime> <sys:datetime>4/2/2015</sys:datetime> </Calendar.SelectedDates> <Calendar.Background> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="#FFE4EAF0" Offset="0"/> <GradientStop Color="#FFECF0F4" Offset="0.16"/> <GradientStop Color="#FFFCFCFD" Offset="0.16"/> <GradientStop Color="#FFD80320" Offset="1"/> </LinearGradientBrush> </Calendar.Background> </Calendar> </Grid> </Window> The select event implementation in C# is as follows: using System; using System.Windows; 49

57 using System.Windows.Controls; namespace WPFCalenderControl /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window public MainWindow() InitializeComponent(); private void Calendar_SelectedDatesChanged(object sender, SelectionChangedEventArgs e) var calendar = sender as Calendar; if (calendar.selecteddate.hasvalue) DateTime date = calendar.selecteddate.value; this.title = date.toshortdatestring(); When you compile and execute the above code, it will produce the following window which shows some of the dates are selected while some are blacked out. 50

58 If you select another date, then it will be shown on the title of this window. We recommend that you execute the above example code and try its other properties and events. 51

59 11. CHECKBOX WPF A checkbox is a control that a user can select (check) or clear (uncheck). It provides a list of options that a user can select, such as a list of settings to apply to an application. The hierarchical inheritance of Checkbox class is as follows: 52

60 Commonly Used Properties of CheckBox Sr. No. 1 Property & Description Background Gets or sets a brush that provides the background of the control. (Inherited from Control) 2 BorderBrush Gets or sets a brush that describes the border fill of a control. (Inherited from Control) 3 BorderThickness Gets or sets the border thickness of a control. (Inherited from Control) 4 Content Gets or sets the content of a ContentControl. (Inherited from ContentControl) 5 ClickMode Gets or sets a value that indicates when the Click event occurs, in terms of device behavior. (Inherited from ButtonBase) 6 ContentTemplate Gets or sets the data template that is used to display the content of the ContentControl. (Inherited from ContentControl) 7 FontFamily Gets or sets the font used to display text in the control. (Inherited from Control) 8 FontSize Gets or sets the size of the text in this control. (Inherited from Control) 9 FontStyle Gets or sets the style in which the text is rendered. (Inherited from Control) 10 FontWeight Gets or sets the thickness of the specified font. (Inherited from Control) 11 Foreground Gets or sets a brush that describes the foreground color. (Inherited from Control) 53

61 12 Height Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement) 13 HorizontalAlignment Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement) 14 IsChecked Gets or sets whether the ToggleButton is checked. (Inherited from ToggleButton) 15 IsEnabled Gets or sets a value indicating whether the user can interact with the control. (Inherited from Control) 16 IsPressed Gets a value that indicates whether a ButtonBase is currently in a pressed state. (Inherited from ButtonBase) 17 IsThreeState Gets or sets a value that indicates whether the control supports three states. (Inherited from ToggleButton) 18 Margin Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement) 19 Name Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAML-declared object by this name. (Inherited from FrameworkElement) 20 Opacity Gets or sets the degree of the object's opacity. (Inherited from UIElement) 21 Resources Gets the locally defined resource dictionary. In XAML, you can establish resource items as child object elements of a frameworkelement.resources property element, through XAML implicit collection syntax. (Inherited from FrameworkElement) 22 Style 54

62 Gets or sets an instance Style that is applied for this object during layout and rendering. (Inherited from FrameworkElement) 23 Template Gets or sets a control template. The control template defines the visual appearance of a control in UI, and is defined in XAML markup. (Inherited from Control) 24 VerticalAlignment Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement) 25 Visibility Gets or sets the visibility of a UIElement. A UIElement that is not visible is not rendered and does not communicate its desired size to layout. (Inherited from UIElement) 26 Width Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement) Commonly Used Methods of CheckBox Sr. No. Method & Description 1 ClearValue Clears the local value of a dependency property. (Inherited from DependencyObject) 2 FindName Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement) 3 OnApplyTemplate Invoked whenever application code or internal processes (such as a rebuilding layout pass) call ApplyTemplate. In simplest terms, this means the method is called just before a UI element displays in your app. Override this method to influence the default post-template logic of a class. (Inherited from FrameworkElement) 55

63 4 OnContentChanged Invoked when the value of the Content property changes. (Inherited from ContentControl) 5 OnDragEnter Called before the DragEnter event occurs. (Inherited from Control) 6 OnDragLeave Called before the DragLeave event occurs. (Inherited from Control) 7 OnDragOver Called before the DragOver event occurs. (Inherited from Control) 8 OnDrop Called before the Drop event occurs. (Inherited from Control) 9 OnGotFocus Called before the GotFocus event occurs. (Inherited from Control) 10 OnKeyDown Called before the KeyDown event occurs. (Inherited from Control) 11 OnKeyUp Called before the KeyUp event occurs. (Inherited from Control) 12 OnLostFocus Called before the LostFocus event occurs. (Inherited from Control) 56

64 13 OnToggle Called when the ToggleButton receives toggle stimulus. (Inherited from ToggleButton) 14 SetBinding Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement) Commonly Used Events of CheckBox Sr. No. Event & Description 1 Checked Fires when a ToggleButton is checked. (Inherited from ToggleButton) 2 Click Occurs when a button control is clicked. (Inherited from ButtonBase) 3 DataContextChanged Occurs when the value of the FrameworkElement.DataContext property changes. (Inherited from FrameworkElement) 4 DragEnter Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement) 5 DragLeave Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement) 6 DragOver Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement) 7 DragStarting Occurs when a drag operation is initiated. (Inherited from UIElement) 8 GotFocus Occurs when a UIElement receives focus. (Inherited from UIElement) 9 Holding Occurs when an otherwise unhandled Hold interaction occurs over the hit test area of this element. (Inherited from UIElement) 10 Intermediate Fires when the state of a ToggleButton is switched to the indeterminate state. (Inherited from ToggleButton) 11 IsEnabledChanged Occurs when the IsEnabled property changes. (Inherited from Control) 12 KeyDown Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement) 57

65 13 KeyUp Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement) 14 LostFocus Occurs when a UIElement loses focus. (Inherited from UIElement) 15 SizeChanged Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement. (Inherited from FrameworkElement) 16 Unchecked Occurs when a ToggleButton is unchecked. (Inherited from ToggleButton) Example 1. Let s create a new WPF project with the name WPFCheckBoxControl. 2. Drag two checkboxes and two textboxes from a toolbox and set the following properties in the properties window. Controls Property Value Checkbox1 Content Two States Name checkbox1 Width 90 Checkbox2 Content Three States Name checkbox2 Width 90 textbox1 Name textbox1 Width 300 Textbox2 Name textbox2 Width Now switch to XAML window in which you will see the XAML tags for check boxes and text boxes. 4. Add some more properties and selection event as shown in the following XAML code. <Window x:class="wpfcheckboxcontrol.mainwindow" <Grid> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfcheckboxcontrol" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <CheckBox x:name="checkbox1" Content="Two States" 58

66 HorizontalAlignment="Left" Margin="80,70,0,0" VerticalAlignment="Top" Checked="HandleCheck" Unchecked="HandleUnchecked" Width="90"/> <CheckBox x:name="checkbox2" Content="Three States" HorizontalAlignment="Left" Margin="80,134,0,0" VerticalAlignment="Top" Width="90" IsThreeState="True" Indeterminate="HandleThirdState" Checked="HandleCheck" Unchecked="HandleUnchecked"/> <TextBox x:name="textbox1" HorizontalAlignment="Left" Height="23" Margin="236,68,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="300"/> <TextBox x:name="textbox2" HorizontalAlignment="Left" Height="23" Margin="236,135,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="300"/> </Grid> </Window> Here is the implementation in C# for different events: using System.Windows; using System.Windows.Controls; namespace WPFCheckBoxControl /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window 59

67 public MainWindow() InitializeComponent(); private void HandleCheck(object sender, RoutedEventArgs e) CheckBox cb = sender as CheckBox; checked."; if (cb.name == "checkbox1") textbox1.text = "2 state CheckBox is else textbox2.text = "3 state CheckBox is checked."; private void HandleUnchecked(object sender, RoutedEventArgs e) CheckBox cb = sender as CheckBox; if (cb.name == "checkbox1") textbox1.text = "2 state CheckBox is unchecked."; else textbox2.text = "3 state CheckBox is unchecked."; private void HandleThirdState(object sender, RoutedEventArgs e) CheckBox cb = sender as CheckBox; textbox2.text = "3 state CheckBox is in indeterminate state."; When you compile and execute the above code, it will produce the following window. When you check / uncheck the checkboxes, it will update the text block accordingly. 60

68 We recommend that you execute the above example code and try some other properties and events of the checkbox control. 61

69 12. COMBOBOX WPF A combobox is a selection control that combines a non-editable textbox and a drop-down listbox that allows users to select an item from a list. It either displays the current selection or is empty if there is no selected item. The hierarchical inheritance of ComboBox class is as follows: Commonly Used Properties of ComboBox Sr. Property & Description No. Background 1 Gets or sets a brush that provides the background of the control. (Inherited from Control) 2 BorderThickness Gets or sets the border thickness of a control. (Inherited from Control) 62

70 3 FontFamily Gets or sets the font used to display text in the control. (Inherited from Control) 4 FontSize Gets or sets the size of the text in this control. (Inherited from Control) 5 FontStyle Gets or sets the style in which the text is rendered. (Inherited from Control) 6 FontWeight Gets or sets the thickness of the specified font. (Inherited from Control) 7 Foreground Gets or sets a brush that describes the foreground color. (Inherited from Control) 8 GroupStyle Gets a collection of GroupStyle objects that define the appearance of each level of groups. (Inherited from ItemsControl) 9 Header Gets or sets the content for the control's header. Height 10 Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement) HorizontalAlignment 11 Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement) IsDropDownOpen 12 Gets or sets a value that indicates whether the drop-down portion of the ComboBox is currently open. IsEditable 13 Gets a value that indicates whether the user can edit text in the text box portion of the ComboBox. This property always returns false. 14 IsEnabled Gets or sets a value indicating whether the user can interact with the control. (Inherited from Control) 15 Margin Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement) 16 Name Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAMLdeclared object by this name. (Inherited from FrameworkElement) 17 Opacity Gets or sets the degree of the object's opacity. (Inherited from UIElement) 18 SelectedIndex Gets or sets the index of the selected item. (Inherited from Selector) 19 SelectedItem Gets or sets the selected item. (Inherited from Selector) SelectedValue 20 Gets or sets the value of the selected item, obtained by using the SelectedValuePath. (Inherited from Selector) Style 21 Gets or sets an instance Style that is applied for this object during layout and rendering. (Inherited from FrameworkElement) VerticalAlignment 22 Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement) 63

71 23 24 Width Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement) ItemsSource Gets or sets an object source used to generate the content of the ItemsControl. (Inherited from ItemsControl) Commonly Used Methods of ComboBox Sr. Method & Description No. Arrange Positions child objects and determines a size for a UIElement. Parent objects 1 that implement custom layout for their child elements should call this method from their layout override implementations to form a recursive layout update. (Inherited from UIElement) FindName 2 Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement) 3 Focus Attempts to set the focus on the control. (Inherited from Control) 4 GetValue Returns the current effective value of a dependency property from a DependencyObject. (Inherited from DependencyObject) 5 IndexFromContainer Returns the index to the item that has the specified, generated container. (Inherited from ItemsControl) 6 OnDragEnter Called before the DragEnter event occurs. (Inherited from Control) 7 OnDragLeave Called before the DragLeave event occurs. (Inherited from Control) 8 OnDragOver Called before the DragOver event occurs. (Inherited from Control) 9 OnDrop Called before the Drop event occurs. (Inherited from Control) 10 OnKeyDown Called before the KeyDown event occurs. (Inherited from Control) 11 OnKeyUp Called before the KeyUp event occurs. (Inherited from Control) 12 OnLostFocus Called before the LostFocus event occurs. (Inherited from Control) ReadLocalValue 13 Returns the local value of a dependency property, if a local value is set. (Inherited from DependencyObject) SetBinding 14 Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement) SetValue 15 Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject) 64

72 Commonly Used Events of ComboBox Sr. Event & Description No. DragEnter 1 Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement) DragLeave 2 Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement) DragOver 3 Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement) 4 DragStarting Occurs when a drag operation is initiated. (Inherited from UIElement) Drop 5 Occurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement) 6 DropCompleted Occurs when a drag-and-drop operation is ended. (Inherited from UIElement) 7 DropDownClosed Occurs when the drop-down portion of the ComboBox closes. 8 DropDownOpened Occurs when the drop-down portion of the ComboBox opens. 9 GotFocus Occurs when a UIElement receives focus. (Inherited from UIElement) 10 IsEnabledChanged Occurs when the IsEnabled property changes. (Inherited from Control) 11 KeyDown Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement) 12 KeyUp Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement) 13 LostFocus Occurs when a UIElement loses focus. (Inherited from UIElement) 14 SelectionChanged Occurs when the currently selected item changes. (Inherited from Selector) SizeChanged 15 Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement. (Inherited from FrameworkElement) Example 1. Let s create a new WPF project with the name WPFComboBoxControl. 2. Drag two comboboxes and two textboxes from a toolbox and set the following properties in the properties window. Controls Property Value Combobox1 iseditable False Name combobox Width 90 Combobox2 iseditable True Name combobox1 65

73 Width 90 Textbox1 Name textbox Width 300 Textbox2 Name textbox1 Width Now switch to XAML window in which you will see the XAML tags for comboboxes and textboxes. 4. Add some more properties combobox items and selection event, as shown in the following XAML code. <Window x:class="wpfcomboboxcontrol.mainwindow" <Grid> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfcomboboxcontrol" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <ComboBox x:name="combobox" HorizontalAlignment="Left" Margin="80,53,0,0" VerticalAlignment="Top" Width="120" SelectionChanged="Combo_SelectionChanged"> <ComboBoxItem Content="Item #1"/> <ComboBoxItem Content="Item #2"/> <ComboBoxItem Content="Item #3"/> </ComboBox> <ComboBox x:name="combobox1" HorizontalAlignment="Left" Margin="80,153,0,0" VerticalAlignment="Top" Width="120" IsEditable="True" SelectionChanged="Combo1_SelectionChanged"> <ComboBoxItem Content="Item #1"/> <ComboBoxItem Content="Item #2"/> <ComboBoxItem Content="Item #3"/> </ComboBox> <TextBox x:name="textbox" HorizontalAlignment="Left" Height="23" Margin="253,53,0,0" TextWrapping="Wrap" 66

74 VerticalAlignment="Top" Width="200"/> <TextBox x:name="textbox1" HorizontalAlignment="Left" Height="23" Margin="253,152,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="200"/> </Grid> </Window> Here is the C# code in which the selection changed events are implemented. using System.Windows; using System.Windows.Controls; namespace WPFComboBoxControl /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window public MainWindow() InitializeComponent(); private void Combo_SelectionChanged(object sender, SelectionChangedEventArgs e) textbox.text = combobox.selecteditem.tostring(); private void Combo1_SelectionChanged(object sender, SelectionChangedEventArgs e) textbox1.text = combobox1.selecteditem.tostring(); 67

75 When you compile and execute the above code, it will produce the following window. When you select an item, it will be displayed on the textbox. We recommend that you execute the above example code and try some other properties and events of the combobox control. 68

76 13. CONTEXTMENU WPF ContextMenu is a pop-up menu that enables a control to expose functionality that is specific to the context of the control. It appears whenever the context menu is requested through a user interface from within this element. The hierarchical inheritance of ContextMenu class is as follows: Commonly Used Properties of ContextMenu Sr. Property & Description No. 1 Background Gets or sets a brush that provides the background of the control. (Inherited from Control) 2 BorderThickness Gets or sets the border thickness of a control. (Inherited from Control) 69

77 3 ContextMenu Gets or sets the context menu element that should appear whenever the context menu is requested through user interface (UI) from within this element. (Inherited from FrameworkElement.) 4 FontFamily Gets or sets the font used to display text in the control. (Inherited from Control) 5 FontSize Gets or sets the size of the text in this control. (Inherited from Control) 6 FontStyle Gets or sets the style in which the text is rendered. (Inherited from Control) 7 FontWeight Gets or sets the thickness of the specified font. (Inherited from Control) Foreground 8 Gets or sets a brush that describes the foreground color. (Inherited from Control) GroupStyle 9 Gets a collection of GroupStyle objects that define the appearance of each level of groups. (Inherited from ItemsControl) HasItems 10 Gets a value that indicates whether the ItemsControl contains items. (Inherited from ItemsControl.) Height 11 Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement) HorizontalAlignment 12 Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement) IsFocused 13 Gets a value that determines whether this element has logical focus. This is a dependency property. (Inherited from UIElement.) 14 IsOpen Gets or sets a value that indicates whether the ContextMenu is visible. IsEnabled 15 Gets or sets a value indicating whether the user can interact with the control. (Inherited from Control) ItemsSource 16 Gets or sets an object source used to generate the content of the ItemsControl. (Inherited from ItemsControl) Margin 17 Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement) Name 18 Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAMLdeclared object by this name. (Inherited from FrameworkElement) 19 Opacity Gets or sets the degree of the object's opacity. (Inherited from UIElement) Style 20 Gets or sets an instance Style that is applied for this object during layout and rendering. (Inherited from FrameworkElement) VerticalAlignment 21 Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement) 70

78 22 Width Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement) Commonly Used Methods of ContextMenu Sr. Method & Description No. AddChild 1 Adds the specified object as the child of the ItemsControl object. (Inherited from ItemsControl.) Arrange Positions child objects and determines a size for a UIElement. Parent objects 2 that implement custom layout for their child elements should call this method from their layout override implementations to form a recursive layout update. (Inherited from UIElement) FindName 3 Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement) 4 Focus Attempts to set the focus on the control. (Inherited from Control) GetValue 5 Returns the current effective value of a dependency property from a DependencyObject. (Inherited from DependencyObject) IsItemItsOwnContainer 6 Determines if the specified item is (or is eligible to be) its own container. (Inherited from ItemsControl.) OnDragEnter 7 Called before the DragEnter event occurs. (Inherited from Control) 8 OnDragLeave Called before the DragLeave event occurs. (Inherited from Control) 9 OnDragOver Called before the DragOver event occurs. (Inherited from Control) 10 OnDrop Called before the Drop event occurs. (Inherited from Control) OnContextMenuOpening 11 Invoked whenever an unhandled ContextMenuClosing routed event reaches this class in its route. Implement this method to add class handling for this event. (Inherited from FrameworkElement.) 12 OnItemsChanged Invoked when the Items property changes. (Inherited from ItemsControl.) 13 OnLostFocus Called before the LostFocus event occurs. (Inherited from Control) ReadLocalValue 14 Returns the local value of a dependency property, if a local value is set. (Inherited from DependencyObject) SetBinding 15 Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement) SetValue 16 Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject) 71

79 Commonly Used Events of ContextMenu Sr. Event & Description No. 1 Closed Occurs when a particular instance of a ContextMenu closes. 2 ContextMenuClosing Occurs just before any context menu on the element is closed. (Inherited from FrameworkElement.) 3 ContextMenuOpening Occurs when any context menu on the element is opened. (Inherited from FrameworkElement.) 4 DataContextChanged Occurs when the data context for this element changes. (Inherited from FrameworkElement.) 5 DragEnter Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement) 6 DragLeave Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement) 7 DragOver Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement) 8 Drop Occurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement) 9 GotFocus Occurs when a UIElement receives focus. (Inherited from UIElement) 10 IsEnabledChanged Occurs when the IsEnabled property changes. (Inherited from Control) 11 KeyDown Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement) 12 KeyUp Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement) 13 LostFocus Occurs when a UIElement loses focus. (Inherited from UIElement) Example 1. Let s create a new WPF project with the name WPFContextMenuControl. 2. Drag a textbox from a toolbox and set the following properties in the properties window. Property Value Name textbox1 Text Hi, this is WPF tutorial TextWraping Wrap Width

80 3. Now switch to XAML window in which you will see the XAML tags for textbox and ContextMenu. 4. Add some more properties, menu items, and checked and unchecked events, as shown in the following XAML code. The following example contains a textbox with ContextMenu which manipulates the text inside the textbox. The following XAML code creates a textbox with some properties and events context menu. <Window x:class="wpfcontextmenucontrol.mainwindow" <Grid> </Grid> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfcontextmenucontrol" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <TextBox x:name="textbox1" HorizontalAlignment="Left" Height="178" Margin="92,61,0,0" TextWrapping="Wrap" Text="Hi, this is WPF tutorial" VerticalAlignment="Top" Width="306"> <TextBox.ContextMenu> <ContextMenu> <MenuItem Header="_Bold" IsCheckable="True" Checked="Bold_Checked" Unchecked="Bold_Unchecked" /> <MenuItem Header="_Italic" IsCheckable="True" <Separator /> Checked="Italic_Checked" Unchecked="Italic_Unchecked" /> <MenuItem Header="Increase Font Size" Click="IncreaseFont_Click" /> <MenuItem Header="_Decrease Font Size" </ContextMenu> </TextBox.ContextMenu> </TextBox> Click="DecreaseFont_Click" /> 73

81 </Window> Here is the implementation in C# for different events. using System.Windows; namespace WPFContextMenuControl /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window public MainWindow() InitializeComponent(); private void Bold_Checked(object sender, RoutedEventArgs e) textbox1.fontweight = FontWeights.Bold; private void Bold_Unchecked(object sender, RoutedEventArgs e) textbox1.fontweight = FontWeights.Normal; private void Italic_Checked(object sender, RoutedEventArgs e) textbox1.fontstyle = FontStyles.Italic; private void Italic_Unchecked(object sender, RoutedEventArgs e) textbox1.fontstyle = FontStyles.Normal; 74

82 private void IncreaseFont_Click(object sender, RoutedEventArgs e) if (textbox1.fontsize < 18) textbox1.fontsize += 2; private void DecreaseFont_Click(object sender, RoutedEventArgs e) if (textbox1.fontsize > 10) textbox1.fontsize -= 2; When you compile and execute the above code, it will produce the following window: We recommend that you execute the above example code and try some other properties and events of ContextMenu. 75

83 14. DATAGRID WPF A DataGrid is a control that displays data in a customizable grid. It provides a flexible way to display a collection of data in rows and columns. The hierarchical inheritance of DataGrid class is as follows: Commonly Used Properties of DataGrid Sr. No. Properties & Description 1 AlternatingRowBackground Gets or sets the background brush for use on alternating rows. 2 AreRowDetailsFrozen Gets or sets a value that indicates whether the row details can scroll horizontally. 76

84 3 AutoGenerateColumns Gets or sets a value that indicates whether the columns are created automatically. 4 CanUserAddRows Gets or sets a value that indicates whether the user can add new rows to the DataGrid. 5 CanUserDeleteRows Gets or sets a value that indicates whether the user can delete rows from the DataGrid. CanUserReorderColumns 6 Gets or sets a value that indicates whether the user can change the column display order by dragging column headers with the mouse. CanUserResizeColumns 7 Gets or sets a value that indicates whether the user can adjust the width of columns by using the mouse. CanUserResizeRows 8 Gets or sets a value that indicates whether the user can adjust the height of rows by using the mouse. CanUserSortColumns 9 Gets or sets a value that indicates whether the user can sort columns by clicking the column header. 10 ColumnHeaderHeight Gets or sets the height of the column headers row. 11 ColumnHeaderStyle Gets or sets the style applied to all column headers in the DataGrid. 12 Columns Gets a collection that contains all the columns in the DataGrid. 13 ColumnWidth Gets or sets the standard width and sizing mode of columns and headers in the DataGrid. 14 CurrentCell Gets or sets the cell that has focus. 15 CurrentColumn Gets or sets the column that contains the current cell. 16 CurrentItem Gets the data item bound to the row that contains the current cell. 17 FrozenColumnCount Gets or sets the number of non-scrolling columns. HorizontalScrollBarVisibility 18 Gets or sets a value that indicates how horizontal scroll bars are displayed in the DataGrid. IsReadOnly 19 Gets or sets a value that indicates whether the user can edit values in the DataGrid. 20 RowBackground Gets or sets the default brush for the row background. 21 RowHeight Gets or sets the suggested height for all rows. 22 SelectedCells Gets the list of cells that are currently selected. 77

85 Commonly Used Methods of DataGrid Sr. No Methods & Description BeginEdit Invokes the BeginEdit command, which will place the current cell or row into edit mode. CancelEdit Invokes the CancelEditCommand command for the cell or row currently in edit mode. ClearDetailsVisibilityForItem Clears the DetailsVisibility property for the DataGridRow that represents the specified data item. ColumnFromDisplayIndex Gets the DataGridColumn at the specified index. CommitEdit Invokes the CommitEditCommand command for the cell or row currently in edit mode. GenerateColumns Generates columns for the specified properties of an object. GetDetailsVisibilityForItem Gets the DetailsVisibility property for the DataGridRow that represents the specified data item. OnApplyTemplate When overridden in a derived class, is invoked whenever application code or internal processes call ApplyTemplate. (Overrides FrameworkElement.OnApplyTemplate().) ScrollIntoView Scrolls the DataGrid vertically to display the row for the specified data item. SelectAllCells Selects all the cells in the DataGrid. SetDetailsVisibilityForItem Sets the value of the DetailsVisibility property for the DataGridRow that contains the specified object. UnselectAllCells Unselects all the cells in the DataGrid. Commonly Used Events of DataGrid Sr. No. Events & Description 1 AddingNewItem Occurs before a new item is added to the DataGrid. 2 AutoGeneratedColumns Occurs when auto generation of all columns is completed. 3 AutoGeneratingColumn Occurs when an individual column is auto-generated. 4 BeginningEdit Occurs before a row or cell enters edit mode. 5 CellEditEnding Occurs before a cell edit is committed or canceled. 6 ColumnDisplayIndexChanged Occurs when the DisplayIndex property on one of the columns changes. ColumnHeaderDragCompleted 7 Occurs when the user releases a column header after dragging it by using the mouse. 78

86 8 ColumnHeaderDragDelta Occurs every time the mouse position changes while the user drags a column header. 9 ColumnHeaderDragStarted Occurs when the user begins dragging a column header by using the mouse. 10 ColumnReordered Occurs when a column moves to a new position in the display order. 11 ColumnReordering Occurs before a column moves to a new position in the display order. 12 CopyingRowClipboardContent Occurs after the default row content is prepared. 13 CurrentCellChanged Occurs when the value of the CurrentCell property has changed. 14 InitializingNewItem Occurs when a new item is created. LoadingRow 15 Occurs after a DataGridRow is instantiated, so that you can customize it before it is used. 16 LoadingRowDetails Occurs when a new row details template is applied to a row. 17 PreparingCellForEdit Occurs when a cell enters edit mode. 18 RowDetailsVisibilityChanged Occurs when the visibility of a row details element changes. 19 RowEditEnding Occurs before a row edit is committed or canceled. 20 SelectedCellsChanged Occurs when the SelectedCells collection changes. 21 Sorting Occurs when a column is being sorted. 22 UnloadingRow Occurs when a DataGridRow object becomes available for reuse. 23 UnloadingRowDetails Occurs when a row details element becomes available for reuse. Example 1. Let s create a new WPF project with WPFDataGridControl name. 2. Drag Data grid from a toolbox. 3. The following example shows how to display data in a DataGrid. Given below is the XAML code in which two data grids are created with a set of properties and events. <Window x:class="wpfdatagridcontrol.mainwindow" xmlns=" xmlns:x=" xmlns:core="clr-namespace:system;assembly=mscorlib" xmlns:local="clr-namespace:wpfdatagridcontrol" Title="MainWindow" Height="350" Width="525"> <Window.Resources> 79

87 <ObjectDataProvider x:key="myenum" MethodName="GetValues" ObjectType="x:Type core:enum"> <ObjectDataProvider.MethodParameters> <x:typeextension Type="local:Party" /> </ObjectDataProvider.MethodParameters> </ObjectDataProvider> </Window.Resources> <Grid> <DataGrid Name="dataGrid" AlternatingRowBackground="LightBlue" AlternationCount="2" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Header="Name" Binding="Binding Name" /> <DataGridTextColumn Header="Title" Binding="Binding Title" /> <DataGridCheckBoxColumn Header="ReElected?" Binding="Binding WasReElected"/> <DataGridComboBoxColumn Header="Party" SelectedItemBinding="Binding Affiliation" Source=StaticResource myenum" /> </DataGrid.Columns> </DataGrid> </Grid> </Window> ItemsSource="Binding Here is the implementation in C# for two different classes. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; 80

88 using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WPFDataGridControl /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window public MainWindow() InitializeComponent(); datagrid.itemssource = Employee.GetEmployees(); public enum Party Indepentent, Federalist, DemocratRepublican, public class Employee : INotifyPropertyChanged private string name; public string Name get return name; set name = value; RaiseProperChanged(); 81

89 private string title; public string Title get return title; set title = value; RaiseProperChanged(); private bool wasreelected; public bool WasReElected get return wasreelected; set wasreelected = value; RaiseProperChanged(); private Party affiliation; public Party Affiliation get return affiliation; set affiliation = value; RaiseProperChanged(); public static ObservableCollection<Employee> GetEmployees() var employees = new ObservableCollection<Employee>(); employees.add(new Employee() Name = "Ali", Title = "Minister", WasReElected = true, Affiliation = Party.Indepentent ); 82

90 employees.add(new Employee() Name = "Ahmed", Title = "CM", WasReElected = false, Affiliation = Party.Federalist ); employees.add(new Employee() Name = "Amjad", Title = "PM", WasReElected = true, Affiliation = Party.DemocratRepublican ); employees.add(new Employee() Name = "Waqas", Title = "Minister", WasReElected = false, Affiliation = Party.Indepentent ); employees.add(new Employee() Name = "Bilal", Title = "Minister", WasReElected = true, Affiliation = Party.Federalist ); employees.add(new Employee() Name = "Waqar", Title = "Minister", WasReElected = false, Affiliation = Party.DemocratRepublican ); return employees; public event PropertyChangedEventHandler PropertyChanged; private void RaiseProperChanged([CallerMemberName] string caller = "") if (PropertyChanged!= null) PropertyChanged(this, new PropertyChangedEventArgs(caller)); 83

91 When you compile and execute the above code, it will produce the following window. We recommend that you execute the above example code and try some of the other properties and events of DataGrid. 84

92 15. DATEPICKER WPF A DatePicker is a control that allows a user to pick a date value. The user picks the date by using ComboBox selection for month, day, and year values. The hierarchical inheritance of DatePicker class is as follows: Commonly Used Properties of DatePicker Sr. No. Property & Description 1 CalendarIdentifier Gets or sets the calendar system to use. 2 CalendarIdentifierProperty Gets the identifier for the CalendarIdentifier dependency property. 3 Date Gets or sets the date currently set in the date picker. 4 DateProperty Gets the identifier for the Date dependency property. 5 DayFormat Gets or sets the display format for the day value. 6 DayFormatProperty Gets the identifier for the DayFormat dependency property. 7 DayVisible Gets or sets a value that indicates whether the day selector is shown. 85

93 8 DayVisibleProperty Gets the identifier for the DayVisible dependency property. 9 Header Gets or sets the content for the control's header. 10 HeaderProperty Identifies the Header dependency property. 11 HeaderTemplate Gets or sets the DataTemplate used to display the content of the control's header. 12 HeaderTemplateProperty Identifies the HeaderTemplate dependency property. 13 MaxYear Gets or sets the maximum Gregorian year available for picking. 14 MaxYearProperty Gets the identifier for the MaxYear dependency property. 15 MinYear Gets or sets the minimum Gregorian year available for picking. 16 MinYearProperty Gets the identifier for the MinYear dependency property. 17 MonthFormat Gets or sets the display format for the month value. 18 MonthFormatProperty Gets the identifier for the MonthFormat dependency property. 19 MonthVisible Gets or sets a value that indicates whether the month selector is shown. 20 MonthVisibleProperty Gets the identifier for the MonthVisible dependency property. Orientation 21 Gets or sets a value that indicates whether the day, month, and year selectors are stacked horizontally or vertically. 22 OrientationProperty Gets the identifier for the Orientation dependency property. 23 YearFormat Gets or sets the display format for the year value. 24 YearFormatProperty Gets the identifier for the YearFormat dependency property. 25 YearVisible Gets or sets a value that indicates whether the year selector is shown. 26 YearVisibleProperty Gets the identifier for the YearVisible dependency property. Commonly Used Events in DatePicker Class Sr. No. Event & Description 1 DateChanged Occurs when the date value is changed. DragEnter 2 Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement) DragLeave 3 Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement) 86

94 DragOver 4 Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement) 5 DragStarting Occurs when a drag operation is initiated. (Inherited from UIElement) 6 GotFocus Occurs when a UIElement receives focus. (Inherited from UIElement) Holding 7 Occurs when an otherwise unhandled Hold interaction occurs over the hit test area of this element. (Inherited from UIElement) 8 IsEnabledChanged Occurs when the IsEnabled property changes. (Inherited from Control) KeyDown 9 Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement) KeyUp 10 Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement) 11 LostFocus Occurs when a UIElement loses focus. (Inherited from UIElement) Commonly Used Methods in DatePicker Class Sr. Method & Description No. ClearValue 1 Clears the local value of a dependency property. (Inherited from DependencyObject) FindName 2 Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement) OnApplyTemplate Invoked whenever application code or internal processes (such as a rebuilding 3 layout pass) call ApplyTemplate. In simplest terms, this means the method is called just before a UI element displays in your app. Override this method to influence the default post-template logic of a class. (Inherited from FrameworkElement) 4 OnDragEnter Called before the DragEnter event occurs. (Inherited from Control) 5 OnDragLeave Called before the DragLeave event occurs. (Inherited from Control) 6 OnDragOver Called before the DragOver event occurs. (Inherited from Control) 7 OnDrop Called before the Drop event occurs. (Inherited from Control) 8 OnGotFocus Called before the GotFocus event occurs. (Inherited from Control) 9 OnKeyDown Called before the KeyDown event occurs. (Inherited from Control) 10 OnKeyUp Called before the KeyUp event occurs. (Inherited from Control) 11 OnLostFocus Called before the LostFocus event occurs. (Inherited from Control) 12 SetBinding 87

95 Example Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement) 1. Let s create a new WPF project with the name WPFDatePickerControl. 2. Drag a DatePicker from the toolbox. 3. The following example shows how to create a DatePicker control. 4. When you click on any date from the DatePicker control, the program will update the title with that date. 5. The following XAML code creates a DatePicker with some properties and click event. <Window x:class="wpfdatepickercontrol.mainwindow" <Grid> </Grid> </Window> xmlns=" xmlns:x=" Title="MainWindow" Height="350" Width="604"> <DatePicker HorizontalAlignment="Center" Margin="10,10,0,0" VerticalAlignment="Top" SelectedDateChanged="DatePicker_SelectedDateChanged"/> Here is the C# implementation for DatePicker_SelectedDateChanged event. using System; using System.Windows; using System.Windows.Controls; namespace WPFDatePickerControl public partial class MainWindow : Window public MainWindow() InitializeComponent(); 88

96 private void DatePicker_SelectedDateChanged(object sender, SelectionChangedEventArgs e) var picker = sender as DatePicker; DateTime? date = picker.selecteddate; if (date == null) this.title = "No date"; else this.title = date.value.toshortdatestring(); When you compile and execute the above code, it will produce the following window. We recommend that you execute the above example code and try some of the other properties and events of the DatePicker class. 89

97 16. DIALOG BOX WPF All standalone applications have a main window that exposes some functionality and displays some data over which the application operates through a GUI. An application may also display additional windows to do the following: Display some specific information to users Gather useful information from users Both display and gather important information Example Let s take an example to understand the concept of Dialog Box. First of all, create a new WPF project with the name WPFDialog. 1. Drag one button and one textbox from the Toolbox. 2. When the user clicks this button, it opens another dialog box with Yes, No, and Cancel buttons and displays a message click any button on it. 3. When a user clicks any of them, this dialog box gets closed and shows a textbox with the information of the button that was clicked. 4. Here is the XAML code to initialize a button and a textbox with some properties. <Window x:class="wpfdialog.mainwindow" <Grid> xmlns=" xmlns:x=" Title="MainWindow" Height="350" Width="604"> <Button Height="23" Margin="100" Name="ShowMessageBox" VerticalAlignment="Top" Click="ShowMessageBox_Click">Show Message Box</Button> <TextBox Height="23" HorizontalAlignment="Left" Margin="181,167,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" /> 90

98 </Grid> </Window> Here is the C# code in which the button click event is implemented. using System; using System.Windows; using System.Windows.Controls; namespace WPFDialog /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window public MainWindow() InitializeComponent(); private void ShowMessageBox_Click(object sender, RoutedEventArgs e) string msgtext = "Click any button"; string txt = "My Title"; MessageBoxButton button = MessageBoxButton.YesNoCancel; MessageBoxResult result = MessageBox.Show(msgtext, txt, button); switch (result) case MessageBoxResult.Yes: textbox1.text = "Yes"; break; case MessageBoxResult.No: textbox1.text = "No"; break; case MessageBoxResult.Cancel: textbox1.text = "Cancel"; break; 91

99 When you compile and execute the above code, it will produce the following window. When you click on the button, it displays another dialog box (as shown below) that prompts the user to click a button. In case the user clicks the Yes button, it updates the textbox with the button content. 92

100 17. GRIDVIEW WPF A GridView is a control that displays data items in rows and columns. Actually a ListView displays data. By default, it contains a GridView. The hierarchical inheritance of GridView class is as follows: Below are the commonly used properties of GridView Sr. No. Property & Description Background 1 Gets or sets a brush that provides the background of the control. (Inherited from Control) 2 BorderThickness Gets or sets the border thickness of a control. (Inherited from Control) 93

101 DataContext 3 Gets or sets the data context for a FrameworkElement when it participates in data binding. (Inherited from FrameworkElement) FontFamily 4 Gets or sets the font used to display text in the control. (Inherited from Control) 5 FontSize Gets or sets the size of the text in this control. (Inherited from Control) 6 FontStyle Gets or sets the style in which the text is rendered. (Inherited from Control) 7 FontWeight Gets or sets the thickness of the specified font. (Inherited from Control) Foreground 8 Gets or sets a brush that describes the foreground color. (Inherited from Control) GroupStyle 9 Gets a collection of GroupStyle objects that define the appearance of each level of groups. (Inherited from ItemsControl) 10 Header Gets or sets the content for the list header. (Inherited from ListViewBase) 11 Height Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement) HorizontalAlignment 12 Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement) HorizontalContentAlignment 13 Gets or sets the horizontal alignment of the control's content. (Inherited from Control) Items 14 Gets the collection used to generate the content of the control. (Inherited from ItemsControl) ItemsSource 15 Gets or sets an object source used to generate the content of the ItemsControl. (Inherited from ItemsControl) ItemTemplate 16 Gets or sets the DataTemplate used to display each item. (Inherited from ItemsControl) Margin 17 Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement) Name 18 Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAML-declared object by this name. (Inherited from FrameworkElement) 19 Opacity Gets or sets the degree of the object's opacity. (Inherited from UIElement) Resources 20 Gets the locally defined resource dictionary. In XAML, you can establish resource items as child object elements of a frameworkelement.resources property element, through XAML implicit collection syntax. (Inherited from FrameworkElement) 21 SelectedIndex Gets or sets the index of the selected item. (Inherited from Selector) 94

102 22 SelectedItem Gets or sets the selected item. (Inherited from Selector) 23 SelectedItems Gets the currently selected items. (Inherited from ListViewBase) SelectedRanges 24 Gets a collection of ItemIndexRange objects that describe the currently selected items in the list. (Inherited from ListViewBase) SelectedValue 25 Gets or sets the value of the selected item, obtained by using the SelectedValuePath. (Inherited from Selector) Style 26 Gets or sets an instance Style that is applied for this object during layout and rendering. (Inherited from FrameworkElement) VerticalAlignment 27 Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement) VerticalContentAlignment 28 Gets or sets the vertical alignment of the control's content. (Inherited from Control) Width 29 Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement) Below are the commonly used events in GridView Sr. No. Event & Description DataContextChanged 1 Occurs when the value of the FrameworkElement.DataContext property changes. (Inherited from FrameworkElement) DragEnter 2 Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement) DragLeave 3 Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement) DragOver 4 Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement) 5 DragStarting Occurs when a drag operation is initiated. (Inherited from UIElement) Drop 6 Occurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement) ImageFailed 7 Occurs when there is an error associated with image retrieval or format. ImageOpened 8 Occurs when the image source is downloaded and decoded with no failure. You can use this event to determine the natural size of the image source. KeyDown 9 Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement) 10 KeyUp 95

103 when a keyboard key is released while the UIElement has focus. (Inherited from UIElement) Commonly used Methods of GridView. Sr. No. Method & Description 1 Arrange Positions child objects and determines a size for a UIElement. Parent objects that implement custom layout for their child elements should call this method from their layout override implementations to form a recursive layout update. (Inherited from UIElement) 2 ClearValue Clears the local value of a dependency property. (Inherited from DependencyObject) 3 FindName Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement) 4 GetValue Returns the current effective value of a dependency property from a DependencyObject. (Inherited from DependencyObject) 5 ReadLocalValue Returns the local value of a dependency property, if a local value is set. (Inherited from DependencyObject) 6 SetBinding Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement) 7 SetValue Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject) Example 1. Let s take an example to understand the concept better. Start by creating a new WPF project with the name WPFGridView. 2. Drag a grid view control from the Toolbox. 3. The following example shows the data in grid like table. 4. The following XAML code creates and implements a GridView. <Window x:class="wpfgridview.mainwindow" <Grid> xmlns=" xmlns:x=" Title="MainWindow" Height="350" Width="525"> <ListView HorizontalAlignment="Left" Height="299" Margin="10,10,0,0" VerticalAlignment="Top" Width="497" Name="MenList"> <ListView.View> 96

104 <GridView> <GridViewColumn Header="Name" DisplayMemberBinding="Binding Name" Width="100"/> <GridViewColumn Header="ID" DisplayMemberBinding="Binding ID" Width="100"/> <GridViewColumn Header="Age" DisplayMemberBinding="Binding Age" Width="100"/> </GridView> </ListView.View> </ListView> </Grid> </Window> Here is the C# implementation in which person class is implemented. using System; using System.Windows; using System.Windows.Controls; namespace WPFGridView /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window public MainWindow() InitializeComponent(); MenList.Items.Add(new Person() Name = "Ali", ID = "123A", Age = 20 ); MenList.Items.Add(new Person() Name = "Akram",ID= "456X", Age = 35 ); MenList.Items.Add(new Person() Name = "Salman",ID="333E", Age = 49 ); 97

105 class Person public string Name get; set; public string ID get; set; public int Age get; set; When you compile and execute the above code, it will produce the following output. We recommend that you execute the above example code and try the other properties and events of GridView. 98

106 18. IMAGE WPF A control that displays an image, you can use either the Image object or the ImageBrush object. An Image object display an image, while an ImageBrush object paints another object with an image. The image source is specified by referring to an image file using several supported formats. It can display the following formats; Bitmap (BMP) Tagged Image File Format (TIFF) Icons (ICO) Joint Photographic Experts Group (JPEG) Graphics Interchange Format (GIF) Portable Network Graphics (PNG) JPEG XR The hierarchical inheritance of Image class is as follows Commonly Used Properties of Image class Sr. No. 1 2 Property & Description CanDrag Gets or sets a value that indicates whether the element can be dragged as data in a drag-and-drop operation. (Inherited from UIElement) Height Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement) 99

107 3 HorizontalAlignment Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement) 3 Margin Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement) 4 Name Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAML-declared object by this name. (Inherited from FrameworkElement) 5 Opacity Gets or sets the degree of the object's opacity. (Inherited from UIElement) 6 PlayToSource Gets the information that is transmitted if the Image is used for a Play To scenario. Resources Gets the locally defined resource dictionary. In XAML, you can establish 7 resource items as child object elements of a frameworkelement.resources property element, through XAML implicit collection syntax. (Inherited from FrameworkElement) 8 SourceProperty Identifies the Source dependency property. 9 Stretch Gets or sets a value that describes how an Image should be stretched to fill the destination rectangle. 10 StretchProperty Identifies the Stretch dependency property. Style 11 Gets or sets an instance Style that is applied for this object during layout and rendering. (Inherited from FrameworkElement) VerticalAlignment 12 Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement) Width 13 Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement) 14 wsource Gets or sets the source for the image. Commonly Used Events of Image Class Sr. No. Event & Description DataContextChanged Occurs when the value of the FrameworkElement.DataContext property changes. (Inherited from FrameworkElement) DragEnter Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement) DragLeave Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement) 100

108 DragOver 4 Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement) 5 DragStarting Occurs when a drag operation is initiated. (Inherited from UIElement) Drop 6 Occurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement) DropCompleted 7 Occurs when a drag-and-drop operation is ended. (Inherited from UIElement) 8 GotFocus Occurs when a UIElement receives focus. (Inherited from UIElement) 9 ImageFailed Occurs when there is an error associated with image retrieval or format. ImageOpened 10 Occurs when the image source is downloaded and decoded with no failure. You can use this event to determine the natural size of the image source. KeyDown 11 Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement) KeyUp 12 Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement) SizeChanged 13 Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement. (Inherited from FrameworkElement) Example 1. Let s create a new WPF project with the name WPFImageControl. 2. First divide the screen into two rows by using Grid.RowDefinition. 3. Drag three Image controls from the Toolbox. 4. The following example shows three images. The first one is a simple image; in the second image, opacity property is set; and in the third image, one Eclipse is painted with an ImageBrush. 5. The XAML code is as follows: <Window x:class="wpfimagecontrol.mainwindow" <Grid> xmlns=" xmlns:x=" Title="MainWindow" Height="500" Width="604"> <Grid.RowDefinitions> <RowDefinition Height="1*"/> <RowDefinition Height="1*"/> 101

109 </Grid.RowDefinitions> <StackPanel Orientation="Horizontal"> <Image Width="200" Source="Images\red_rock_01.jpg" VerticalAlignment="Top" Margin="30"/> <Image Width="200" Source="Images\red_rock_01.jpg" VerticalAlignment="Top" Margin="30" Opacity="0.5"/> </StackPanel> <StackPanel Grid.Row="1"> <Ellipse Height="100" Width="200" HorizontalAlignment="Center" Margin="30"> <Ellipse.Fill> <ImageBrush ImageSource="Images\tahoe_01.jpg" /> </Ellipse.Fill> </Ellipse> </StackPanel> </Grid> </Window> 102

110 When you compile and execute the above code, it will produce the following window: We recommend that you execute the above example code and try the other properties and events of the Image class. 103

111 19. LABEL WPF The Label class provides both functional and visual support for access keys (also known as mnemonics). It is frequently used to enable quick keyboard access to controls. The hierarchical inheritance of Label class is as follows: Below are the commonly used properties of Label class Sr. No Property & Description Background Gets or sets a brush that describes the background of a control. (Inherited from Control.) Content Gets or sets the content of a ContentControl. (Inherited from ContentControl.) ContentStringFormat Gets or sets a composite string that specifies how to format the Content property if it is displayed as a string.(inherited from ContentControl.) ContentTemplate Gets or sets the data template used to display the content of the ContentControl. (Inherited from ContentControl.) 104

112 ContextMenu 5 Gets or sets the context menu element that should appear whenever the context menu is requested through user interface (UI) from within this element.(inherited from FrameworkElement.) 6 FontFamily Gets or sets the font family of the control. (Inherited from Control.) 7 FontSize Gets or sets the font size. (Inherited from Control.) 8 FontStyle Gets or sets the font style. (Inherited from Control.) FontWeight 9 Gets or sets the weight or thickness of the specified font. (Inherited from Control.) Foreground 10 Gets or sets a brush that describes the foreground color. (Inherited from Control.) Height 11 Gets or sets the suggested height of the element.(inherited from FrameworkElement.) Margin 12 Gets or sets the outer margin of an element.(inherited from FrameworkElement.) Name 13 Gets or sets the identifying name of the element. The name provides a reference so that code-behind, such as event handler code, can refer to a markup element after it is constructed during processing by a XAML processor.(inherited from FrameworkElement.) Resources 14 Gets or sets the locally-defined resource dictionary. (Inherited from FrameworkElement.) Style 15 Gets or sets the style used by this element when it is rendered. (Inherited from FrameworkElement.) Target 16 Gets or sets the element that receives focus when the user presses the label's. GTMT 17 Template Gets or sets a control template. (Inherited from Control.) Width 18 Gets or sets the width of the element.(inherited from FrameworkElement.) Commonly Used Events of Label Class Sr. No. Event & Description 1 ContextMenuOpening Occurs when the system processes an interaction that displays a context menu. 2 DragEnter Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement) 3 DragLeave Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement) 105

113 DragOver 4 Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement) Drop 5 Occurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement) 6 GotFocus Occurs when a UIElement receives focus. (Inherited from UIElement) KeyDown 7 Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement) KeyUp 8 Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement) SizeChanged 9 Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement. (Inherited from FrameworkElement) Commonly Used Methods in Label Class Sr. Method & Description No. 1 Focus Focuses the TextBlock, as if it were a conventionally focusable control. 2 ToString Returns the string representation of a Control object. (Inherited from Control.) Example 1. Let s create a new WPF project with the name WPFLabelControl. 2. Drag one label control from the Toolbox. 3. Change the different properties of label from the properties window, as shown in the following XAML code. <Window x:class="wpflabelcontrol.mainwindow" <Grid> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpflabelcontrol" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <Label x:name="label" Content="Label Example in WPF" HorizontalAlignment="Left" Margin="71,82,0,0" VerticalAlignment="Top" Height="135" Width="474" 106

114 Background="#FFD6BEBE" FontFamily="Snap ITC" FontSize="36" FontStyle="Italic" FontWeight="Light" Foreground="#FFBD6B6B"/> </Grid> </Window> When you compile and execute the above code, it will produce the following window. 107

115 20. LISTBOX WPF ListBox is a control that provides a list of items to the user item selection. A user can select one or more items from the predefined list of items at a time. In a ListBox, multiple options are always visible to the user without any user interaction. The hierarchical inheritance of ListBox class is as follows: Below are the commonly used Properties of ListBox class Sr. No Property & Description Background Gets or sets a brush that provides the background of the control. (Inherited from Control) BorderThickness Gets or sets the border thickness of a control. (Inherited from Control) FontFamily Gets or sets the font used to display text in the control. (Inherited from Control) FontSize Gets or sets the size of the text in this control. (Inherited from Control) 108

116 FontStyle Gets or sets the style in which the text is rendered. (Inherited from Control) FontWeight Gets or sets the thickness of the specified font. (Inherited from Control) Foreground Gets or sets a brush that describes the foreground color. (Inherited from Control) GroupStyle Gets a collection of GroupStyle objects that define the appearance of each level of groups. (Inherited from ItemsControl) Height Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement) HorizontalAlignment Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement) IsEnabled Gets or sets a value indicating whether the user can interact with the control. (Inherited from Control) Item Gets the collection used to generate the content of the control. (Inherited from ItemsControl) ItemsSource Gets or sets an object source used to generate the content of the ItemsControl. (Inherited from ItemsControl) Margin Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement) Name Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAMLdeclared object by this name. (Inherited from FrameworkElement) Opacity Gets or sets the degree of the object's opacity. (Inherited from UIElement) SelectedIndex Gets or sets the index of the selected item. (Inherited from Selector) SelectedItem Gets or sets the selected item. (Inherited from Selector) SelectedValue Gets or sets the value of the selected item, obtained by using the SelectedValuePath. (Inherited from Selector) Style Gets or sets an instance Style that is applied for this object during layout and rendering. (Inherited from FrameworkElement) VerticalAlignment Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement) Width Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement) 109

117 Commonly Used Events of ListBox Sr. No Event & Description DragEnter Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement) DragLeave Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement) DragOver Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement) DragStarting Occurs when a drag operation is initiated. (Inherited from UIElement) Drop Occurs when the input system reports an underlying drop event with this element as the drop target. (Inherited from UIElement) DropCompleted Occurs when a drag-and-drop operation is ended. (Inherited from UIElement) GotFocus Occurs when a UIElement receives focus. (Inherited from UIElement) IsEnabledChanged Occurs when the IsEnabled property changes. (Inherited from Control) KeyDown Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement) KeyUp Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement) LostFocus Occurs when a UIElement loses focus. (Inherited from UIElement) SelectionChanged Occurs when the currently selected item changes. (Inherited from Selector) SizeChanged Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement. (Inherited from FrameworkElement) Commonly Used Methods of ListBox Sr. Method & Description No. Arrange Positions child objects and determines a size for a UIElement. Parent objects 1 that implement custom layout for their child elements should call this method from their layout override implementations to form a recursive layout update. (Inherited from UIElement) FindName 2 Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement) 3 Focus Attempts to set the focus on the control. (Inherited from Control) GetValue 4 Returns the current effective value of a dependency property from a DependencyObject. (Inherited from DependencyObject) 110

118 5 IndexFromContainer Returns the index to the item that has the specified, generated container. (Inherited from ItemsControl) 6 OnDragEnter Called before the DragEnter event occurs. (Inherited from Control) 7 OnDragLeave Called before the DragLeave event occurs. (Inherited from Control) 8 OnDragOver Called before the DragOver event occurs. (Inherited from Control) 9 OnDrop Called before the Drop event occurs. (Inherited from Control) 10 OnKeyDown Called before the KeyDown event occurs. (Inherited from Control) 11 OnKeyUp Called before the KeyUp event occurs. (Inherited from Control) 12 OnLostFocus Called before the LostFocus event occurs. (Inherited from Control) ReadLocalValue 13 Returns the local value of a dependency property, if a local value is set. (Inherited from DependencyObject) SetBinding 14 Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement) SetValue 15 Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject) Example 1. Let s create a new WPF project with the name WPFListBoxControl. 2. Drag one list box and one textbox from the Toolbox. 3. When the user selects any item from the ListBox, it displayed on the TextBox as well. 4. Here is the XAML code in which a ListBox and a TextBox is created and initialized with some properties. <Window x:class="wpflistboxcontrol.mainwindow" <Grid> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpflistboxcontrol" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <ListBox Name="listbox" Margin="118,77,293,103"> 111

119 <ListBoxItem Content="XAML Tutorials"/> <ListBoxItem Content="WPF Tutorials"/> <ListBoxItem Content="Silverlight Tutorials"/> <ListBoxItem Content="Windows 10 Tutorials"/> <ListBoxItem Content="iOS Tutorials"/> </ListBox> <TextBox Height="23" x:name="textbox1" Width="120" Margin="361,116,0,0" HorizontalAlignment="Left" VerticalAlignment="Top" Text="Binding SelectedItem.Content, ElementName=listbox" /> </Grid> </Window> When the above code is compiled and executed, it will produce the following output: We recommend that you execute the above example code and try the other properties and events of ListBox control. 112

120 21. MENU WPF Menu is a control that enables you to hierarchically organize elements associated with the commands and event handlers. Menu is an ItemsControl, so it can contain a collection of any object type such as string, image, or panel. The hierarchical inheritance of Menu class is as follows: Below are the commonly used properties on Menu class Sr. No. 1 2 Name & Description Background Gets or sets a brush that describes the background of a control. (Inherited from Control.) BindingGroup Gets or sets the BindingGroup that is used for the element. (Inherited from FrameworkElement.) 113

121 BitmapEffect 3 Obsolete. Gets or sets a bitmap effect that applies directly to the rendered content for this element. This is a dependency property. (Inherited from UIElement.) 4 BorderThickness Gets or sets the border thickness of a control. (Inherited from Control.) ContextMenu 5 Gets or sets the context menu element that should appear whenever the context menu is requested through user interface (UI) from within this element. (Inherited from FrameworkElement.) 6 Effect Gets or sets the bitmap effect to apply to the UIElement. This is a dependency property. (Inherited from UIElement.) Height 7 Gets or sets the suggested height of the element. (Inherited from FrameworkElement.) IsMainMenu 8 Gets or sets a value that indicates whether this Menu receives a main menu activation notification. Items 9 Gets the collection used to generate the content of the ItemsControl. (Inherited from ItemsControl.) ItemsPanel 10 Gets or sets the template that defines the panel that controls the layout of items. (Inherited from ItemsControl.) ItemsSource 11 Gets or sets a collection used to generate the content of the ItemsControl. (Inherited from ItemsControl.) ItemStringFormat 12 Gets or sets a composite string that specifies how to format the items in the ItemsControl if they are displayed as strings. (Inherited from ItemsControl.) ItemTemplate 13 Gets or sets the DataTemplate used to display each item. (Inherited from ItemsControl.) ToolTip 14 Gets or sets the tool-tip object that is displayed for this element in the user interface (UI). (Inherited from FrameworkElement.) VerticalContentAlignment 15 Gets or sets the vertical alignment of the control's content. (Inherited from Control.) 16 Width Gets or sets the width of the element. (Inherited from FrameworkElement.) Commonly Used Events in Menu Class Sr. No. Event & Description 1 2 ContextMenuClosing Occurs just before any context menu on the element is closed. (Inherited from FrameworkElement.) ContextMenuOpening Occurs when any context menu on the element is opened. (Inherited from FrameworkElement.) 114

122 KeyDown Occurs when a key is pressed while focus is on this element. (Inherited from UIElement.) KeyUp Occurs when a key is released while focus is on this element. (Inherited from UIElement.) ToolTipClosing Occurs just before any tooltip on the element is closed. (Inherited from FrameworkElement.) ToolTipOpening Occurs when any tooltip on the element is opened. (Inherited from FrameworkElement.) TouchDown Occurs when a finger touches the screen while the finger is over this element. (Inherited from UIElement.) TouchEnter Occurs when a touch moves from outside to inside the bounds of this element. (Inherited from UIElement.) TouchLeave Occurs when a touch moves from inside to outside the bounds of this element. (Inherited from UIElement.) TouchMove Occurs when a finger moves on the screen while the finger is over this element. (Inherited from UIElement.) TouchUp Occurs when a finger is raised off of the screen while the finger is over this element. (Inherited from UIElement.) Example 1. Let s create a new WPF project with the name WPFMenuControl. 2. Drag a menu control from the Toolbox to the design window. 3. The following example contains three menu options with some menu items. When the user clicks an item, the program updates the title. Here is the XAML code: <Window x:class="wpfmenucontrol.mainwindow" <Grid> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfmenucontrol" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <Menu HorizontalAlignment="Left" VerticalAlignment="Top" Width="517"> <MenuItem Header="File"> <MenuItem Header="Item 1" HorizontalAlignment="Left" Width="140" 115

123 Click="MenuItem_Click"/> <MenuItem Header="Item 2" HorizontalAlignment="Left" Width="140" Click="MenuItem_Click"/> <Separator HorizontalAlignment="Left" Width="140"/> <MenuItem Header="Item 3" HorizontalAlignment="Left" Width="140" Click="MenuItem_Click"/> </MenuItem> <MenuItem Header="Edit"> <MenuItem Header="Item 1" HorizontalAlignment="Left" Width="140" Click="MenuItem_Click1"/> <MenuItem Header="Item 2" HorizontalAlignment="Left" Width="140" Click="MenuItem_Click1"/> <Separator HorizontalAlignment="Left" Width="140"/> <MenuItem Header="Item 3" HorizontalAlignment="Left" Width="140" Click="MenuItem_Click1"/> </MenuItem> <MenuItem Header="View"> <MenuItem Header="Item 1" HorizontalAlignment="Left" Width="140" Click="MenuItem_Click2"/> <MenuItem Header="Item 2" HorizontalAlignment="Left" Width="140" Click="MenuItem_Click2"/> <Separator HorizontalAlignment="Left" Width="140"/> <MenuItem Header="Item 3" HorizontalAlignment="Left" Width="140" Click="MenuItem_Click2"/> </MenuItem> </Menu> </Grid> </Window> Here is the events implementation in C#. using System.Windows; using System.Windows.Controls; namespace WPFMenuControl /// <summary> /// Interaction logic for MainWindow.xaml 116

124 /// </summary> public partial class MainWindow : Window public MainWindow() InitializeComponent(); private void MenuItem_Click(object sender, RoutedEventArgs e) MenuItem item = sender as MenuItem; this.title = "File: " + item.header; private void MenuItem_Click1(object sender, RoutedEventArgs e) MenuItem item = sender as MenuItem; this.title = "Edit: " + item.header; private void MenuItem_Click2(object sender, RoutedEventArgs e) MenuItem item = sender as MenuItem; this.title = "View: " + item.header; When you compile and execute the above code, it will produce the following output: 117

125 We recommend that you execute the above example code and try the other properties and events of Menu class. 118

126 22. PASSWORDBOX WPF PasswordBox is a control that allows the user to enter masked passwords. When the user enters a password, it will be displayed as password characters. You can change the Password character by setting the PasswordChar property. The hierarchical inheritance of PasswordBox class is as follows: Commonly Used Properties of PasswordBox Class Sr. No. Property & Description 1 InputScope Gets or sets the context for input used by this PasswordBox. 2 InputScopeProperty Identifies the InputScope dependency property. IsPasswordRevealButtonEnabled 3 Gets or sets a value that specifies whether the visual UI of the PasswordBox includes a button element that toggles showing or hiding the typed characters. In Windows 10 and later, use PasswordRevealMode instead. 4 IsPasswordRevealButtonEnabledProperty Identifies the IsPasswordRevealButtonEnabled dependency property. MaxLength 5 Gets or sets the maximum length for passwords to be handled by this PasswordBox. 6 MaxLengthProperty 119

127 Identifies the MaxLength dependency property. 7 Password Gets or sets the password currently held by the PasswordBox. 8 PasswordChar Gets or sets the masking character for the PasswordBox. 9 PasswordCharProperty Identifies the PasswordChar dependency property. 10 PasswordProperty Identifies the Password dependency property. PasswordRevealMode 11 Gets or sets a value that specifies whether the password is always, never, or optionally obscured. 12 PasswordRevealModeProperty Identifies the PasswordRevealMode dependency property. Resources Gets the locally defined resource dictionary. In XAML, you can establish 13 resource items as child object elements of a frameworkelement.resources property element, through XAML implicit collection syntax. (Inherited from FrameworkElement) Commonly Used Events of PasswordBox Class Sr. No. Event & Description 1 ContextMenuOpening Occurs when the system processes an interaction that displays a context menu. 2 GotFocus Occurs when a UIElement receives focus. (Inherited from UIElement) 3 PasswordChanged Occurs when the value of the Password property changes. 4 Paste Occurs when text is pasted into the control. Below are the commonly used Methods of PasswordBox class. Sr. No. Method & Description 1 OnLostFocus Called before the LostFocus event occurs. (Inherited from Control) 2 SelectAll Selects all the characters in the PasswordBox. 3 SetBinding Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement) 4 SetValue Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject) The following example shows the PasswordBox, labels, and button. Here is the XAML code in which all these controls are created and initialized. <Window x:class="passwordbox.mainwindow" xmlns=" 120

128 <Grid > </Grid> </Window> xmlns:x=" Title="MainWindow" Height="350" Width="604"> <PasswordBox x:name="pwbox" Height="35" Width="200" MaxLength="8" <Label Content="Password" Margin="159,55,158,229" /> HorizontalAlignment="Left" Margin="108,61,0,0" VerticalAlignment="Top" Width="70" /> <Button Content="Ok" HorizontalAlignment="Left" Margin="406,64,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/> <Label Name="statusText" HorizontalAlignment="Left" Margin="159,128,0,0" VerticalAlignment="Top" Width="200" Height="38"/> Here is the button click event implementation in C# in which the program compares if the entered password is wpf12345 then it will display the correct password message on the textblock. using System.Windows; namespace WPFPasswordBoxControl /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> 121

129 public partial class MainWindow : Window public MainWindow() InitializeComponent(); private void Button_Click(object sender, RoutedEventArgs e) if (pwbox.password.tostring() == "wpf12345") statustext.text = "Password Accepted"; else statustext.text = "Wrong Password"; When the above code is compiled and executed, it will produce the following window: We recommend that you execute the above example code and try the other properties and events of PasswordBox class. 122

130 23. POPUP WPF Popup is a control that displays content on top of existing content, within the bounds of the application window. It is a temporary display on other content. The hierarchical inheritance of Popup class is as follows: Commonly Used Properties of Popup Class Sr. No. Property & Description 1 Child Gets or sets the content to be hosted in the popup. 2 ChildProperty Gets the identifier for the Child dependency property. ChildTransitions 3 Gets or sets the collection of Transition style elements that apply to child content of a Popup. 4 ChildTransitionsProperty Identifies the ChildTransitions dependency property. HorizontalOffset 5 Gets or sets the distance between the left side of the application window and the left side of the popup. 6 HorizontalOffsetProperty Gets the identifier for the HorizontalOffset dependency property. 7 IsLightDismissEnabled Gets or sets a value that determines how the Popup can be dismissed. 8 IsLightDismissEnabledProperty Identifies the IsLightDismissEnabled dependency property. 9 IsOpen 123

131 Gets or sets whether the popup is currently displayed on the screen. 10 IsOpenProperty Gets the identifier for the IsOpen dependency property. 11 VerticalOffset Gets or sets the distance between the top of the application window and the top of the popup. 12 VerticalOffsetProperty Gets the identifier for the VerticalOffset dependency property. Commonly Used Events of Popup Class Sr. No. Event & Description 1 Closed Fires when the IsOpen property is set to false. 2 Opened Fires when the IsOpen property is set to true. Example 1. Let s create a new WPF project with the name WPFPopupControl. 2. When you look at the Toolbox, you will observe that there is no popup control. But you can add a popup control to you app from XAML. 3. The following example shows how to use Popup control. Here is the XAML code in which a Popup control and a CheckBox is created and initialized. When the user checks the CheckBox, it displays a Popup. <Window x:class="wpfpopupcontrol.mainwindow" <Grid> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfpopupcontrol" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <CheckBox Name="PCheckBox" Margin="198,94,208,194" Content="Checked Me"/> <Popup IsOpen="Binding ElementName=PCheckBox,Path=IsChecked" PlacementTarget="Binding ElementName=PCheckBox" AllowsTransparency="True" PopupAnimation="Slide"> <Canvas Width="125" Height="100" Background="LightGray"> <Canvas.RenderTransform> 124

132 </Grid> </Window> </Popup> <RotateTransform x:name="thetransform" /> </Canvas.RenderTransform> <TextBlock TextWrapping="Wrap" </Canvas> Foreground="Blue" Text="Hi, this is Popup"/> When you compile and execute the above code, it will produce the following output. When you tick the checkbox, a popup will appear; and when you uncheck the checkbox, the popup will disappear. We recommend that you execute the above example code and try the other properties and events of popup class. 125

133 24. PROGRESSBAR WPF ProgressBar is a control that indicates the progress of an operation, where the typical visual appearance is a bar that animates a filled area as the progress continues. It can show the progress in one of the two following styles: A bar that displays a repeating pattern, or A bar that fills based on a value. The hierarchical inheritance of ProgressBar class is as follows: Commonly Used Properties of ProgressBar Sr. No. Property & Description IsIndeterminate 1 Gets or sets a value that indicates whether the progress bar reports generic progress with a repeating pattern or reports progress based on the Value property. 2 IsIndeterminateProperty Identifies the IsIndeterminate dependency property. 3 ShowError Gets or sets a value that indicates whether the progress bar should use visual states that communicate an Error state to the user. 126

134 4 ShowErrorProperty Identifies the ShowError dependency property. 5 ShowPaused Gets or sets a value that indicates whether the progress bar should use visual states that communicate a Paused state to the user. 6 ShowPausedProperty Identifies the ShowPaused dependency property. 7 TemplateSettings Gets an object that provides calculated values that can be referenced as TemplateBinding sources when defining templates for a ProgressBar control. Commonly Used Events in ProgressBar Class Sr. No. Event & Description 1 ManipulationCompleted Occurs when a manipulation on the UIElement is complete. (Inherited from UIElement) 2 ManipulationDelta Occurs when the input device changes position during a manipulation. (Inherited from UIElement) 3 ManipulationInertiaStarting Occurs when the input device loses contact with the UIElement object during a manipulation and inertia begins. (Inherited from UIElement) 4 ManipulationStarted Occurs when an input device begins a manipulation on the UIElement. (Inherited from UIElement) 5 ManipulationStarting Occurs when the manipulation processor is first created. (Inherited from UIElement) 6 ValueChanged Occurs when the range value changes. (Inherited from RangeBase) Commonly Used Methods in ProgressBar Class Sr. No. Method & Description OnManipulationCompleted 1 Called before the ManipulationCompleted event occurs. (Inherited from Control) 2 OnManipulationDelta Called before the ManipulationDelta event occurs. (Inherited from Control) 3 OnManipulationInertiaStarting Called before the ManipulationInertiaStarting event occurs. (Inherited from Control) 4 OnManipulationStarted Called before the ManipulationStarted event occurs. (Inherited from Control) 5 OnManipulationStarting Called before the ManipulationStarting event occurs. (Inherited from Control) 6 OnMaximumChanged Called when the Maximum property changes. (Inherited from RangeBase) 7 OnMinimumChanged Called when the Minimum property changes. (Inherited from RangeBase) 8 OnValueChanged Fires the ValueChanged routed event. (Inherited from RangeBase) 9 SetBinding 127

135 Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement) 10 SetValue Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject) Example 1. Let s create a new WPF project with the name WPFProgressBarControl. 2. The following example shows how to use the ProgressBar control. Here is the XAML code in which two ProgressBar controls are created and initialized. <Window x:class="wpfprogressbarcontrol.mainwindow" <Grid> </Grid> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfprogressbarcontrol" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <StackPanel x:name="layoutroot" Margin="20"> <Border BorderThickness="5" BorderBrush="Green"> <StackPanel Background="White"> <TextBlock HorizontalAlignment="Center" Margin="10" Text="Value-Based Progress Bar" /> <ProgressBar x:name="pg1" Value="100" Margin="10" Maximum="200" Height="15" IsIndeterminate="False" /> </StackPanel> </Border> <Border BorderThickness="5" BorderBrush="Green"> <StackPanel Background="White"> <TextBlock HorizontalAlignment="Center" Margin="10" Text="Indeterminate Progress Bar" /> <ProgressBar x:name="pg2" Margin="10" Height="15" IsIndeterminate="True" /> </StackPanel> </Border> </StackPanel> 128

136 </Window> When you compile and execute the above code, it will produce the following window. We recommend that you execute the above example code and try the other properties and events of the ProgressBar class. 129

137 25. RADIOBUTTON WPF A Radio Button is a control that allows a user to select a single option from a group of options. The user is limited to select a single option from a related list of options which are mutually exclusive. It has only two options; Selected Cleared The hierarchical inheritance of RadioButton class is as follows: 130

138 Commonly Used Properties of RadioButton Sr. Property & Description No. 1 Background Gets or sets a brush that provides the background of the control. (Inherited from Control) 2 BorderBrush Gets or sets a brush that describes the border fill of a control. (Inherited from Control) 3 BorderThickness Gets or sets the border thickness of a control. (Inherited from Control) 4 Content Gets or sets the content of a ContentControl. (Inherited from ContentControl) 5 ClickMode Gets or sets a value that indicates when the Click event occurs, in terms of device behavior. (Inherited from ButtonBase) 6 ContentTemplate Gets or sets the data template that is used to display the content of the ContentControl. (Inherited from ContentControl) 7 FontFamily Gets or sets the font used to display text in the control. (Inherited from Control) 8 FontSize Gets or sets the size of the text in this control. (Inherited from Control) 9 FontStyle Gets or sets the style in which the text is rendered. (Inherited from Control) 10 FontWeight Gets or sets the thickness of the specified font. (Inherited from Control) 11 Foreground Gets or sets a brush that describes the foreground color. (Inherited from Control) 12 Height Gets or sets the suggested height of a FrameworkElement. (Inherited from FrameworkElement) 13 HorizontalAlignment Gets or sets the horizontal alignment characteristics that are applied to a FrameworkElement when it is composed in a layout parent, such as a panel or items control. (Inherited from FrameworkElement) 14 IsChecked Gets or sets whether the ToggleButton is checked. (Inherited from ToggleButton) 15 IsEnabled Gets or sets a value indicating whether the user can interact with the control. (Inherited from Control) 16 IsPressed Gets a value that indicates whether a ButtonBase is currently in a pressed state. (Inherited from ButtonBase) 17 IsThreeState Gets or sets a value that indicates whether the control supports three states. (Inherited from ToggleButton) 18 Margin Gets or sets the outer margin of a FrameworkElement. (Inherited from FrameworkElement) 131

139 19 Name Gets or sets the identifying name of the object. When a XAML processor creates the object tree from XAML markup, run-time code can refer to the XAML-declared object by this name. (Inherited from FrameworkElement) 20 Opacity Gets or sets the degree of the object's opacity. (Inherited from UIElement) 21 Resources Gets the locally defined resource dictionary. In XAML, you can establish resource items as child object elements of a frameworkelement.resources property element, through XAML implicit collection syntax. (Inherited from FrameworkElement) Style 22 Gets or sets an instance Style that is applied for this object during layout and rendering. (Inherited from FrameworkElement) Template 23 Gets or sets a control template. The control template defines the visual appearance of a control in UI, and is defined in XAML markup. (Inherited from Control) VerticalAlignment 24 Gets or sets the vertical alignment characteristics that are applied to a FrameworkElement when it is composed in a parent object such as a panel or items control. (Inherited from FrameworkElement) Visibility 25 Gets or sets the visibility of a UIElement. A UIElement that is not visible is not rendered and does not communicate its desired size to layout. (Inherited from UIElement) Width 26 Gets or sets the width of a FrameworkElement. (Inherited from FrameworkElement) Commonly Used Methods of RadioButton Sr. Method & Description No. ClearValue 1 Clears the local value of a dependency property. (Inherited from DependencyObject) FindName 2 Retrieves an object that has the specified identifier name. (Inherited from FrameworkElement) OnApplyTemplate Invoked whenever application code or internal processes (such as a rebuilding 3 layout pass) call ApplyTemplate. In simplest terms, this means the method is called just before a UI element displays in your app. Override this method to influence the default post-template logic of a class. (Inherited from FrameworkElement) OnContentChanged 4 Invoked when the value of the Content property changes. (Inherited from ContentControl) 5 OnDragEnter Called before the DragEnter event occurs. (Inherited from Control) 6 OnDragLeave Called before the DragLeave event occurs. (Inherited from Control) 7 OnDragOver Called before the DragOver event occurs. (Inherited from Control) 132

140 8 OnDrop Called before the Drop event occurs. (Inherited from Control) 9 OnGotFocus Called before the GotFocus event occurs. (Inherited from Control) 10 OnKeyDown Called before the KeyDown event occurs. (Inherited from Control) 11 OnKeyUp Called before the KeyUp event occurs. (Inherited from Control) 12 OnLostFocus Called before the LostFocus event occurs. (Inherited from Control) 13 OnToggle Called when the ToggleButton receives toggle stimulus. (Inherited from ToggleButton) 14 SetBinding Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement) Commonly Used Events of RadioButton Sr. Event & Description No. 1 Checked Fires when a ToggleButton is checked. (Inherited from ToggleButton) 2 Click Occurs when a button control is clicked. (Inherited from ButtonBase) 3 DataContextChanged Occurs when the value of the FrameworkElement.DataContext property changes. (Inherited from FrameworkElement) 4 DragEnter Occurs when the input system reports an underlying drag event with this element as the target. (Inherited from UIElement) 5 DragLeave Occurs when the input system reports an underlying drag event with this element as the origin. (Inherited from UIElement) 6 DragOver Occurs when the input system reports an underlying drag event with this element as the potential drop target. (Inherited from UIElement) 7 DragStarting Occurs when a drag operation is initiated. (Inherited from UIElement) 8 GotFocus Occurs when a UIElement receives focus. (Inherited from UIElement) 9 Holding Occurs when an otherwise unhandled Hold interaction occurs over the hit test area of this element. (Inherited from UIElement) 10 Intermediate Fires when the state of a ToggleButton is switched to the indeterminate state. (Inherited from ToggleButton) 11 IsEnabledChanged Occurs when the IsEnabled property changes. (Inherited from Control) 12 KeyDown Occurs when a keyboard key is pressed while the UIElement has focus. (Inherited from UIElement) 13 KeyUp Occurs when a keyboard key is released while the UIElement has focus. (Inherited from UIElement) 133

141 14 LostFocus Occurs when a UIElement loses focus. (Inherited from UIElement) 15 SizeChanged Occurs when either the ActualHeight or the ActualWidth property changes value on a FrameworkElement. (Inherited from FrameworkElement) 16 Unchecked Occurs when a ToggleButton is unchecked. (Inherited from ToggleButton) Example 1. Let s create a new WPF project with the name WPFDialog. 2. Drag five radio buttons and four text blocks from the Toolbox and arrange them as shown in the following XAML code. 3. The following example shows how to use a RadioButton. We will display two groups of RadioButton. When a user selects an option, then the program will display the message on a TextBlock. Here is the XAML code. <Window x:class="wpfradiobuttoncontrol.mainwindow" <Grid> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfradiobuttoncontrol" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <TextBlock x:name="textblock" HorizontalAlignment="Left" Margin="23,68,0,0" TextWrapping="Wrap" Text="Gender:" VerticalAlignment="Top" Width="83"/> <TextBlock x:name="textblock1" HorizontalAlignment="Left" Margin="23,134,0,0" TextWrapping="Wrap" Text="Marital Status:" VerticalAlignment="Top" Width="83"/> <RadioButton x:name="rb1" Content="Male" HorizontalAlignment="Left" Margin="126,68,0,0" VerticalAlignment="Top" GroupName="Gender" Width="69" Checked="HandleCheck"/> <RadioButton x:name="rb2" Content="Female" HorizontalAlignment="Left" Margin="201,68,0,0" VerticalAlignment="Top" GroupName="Gender" Width="81" Checked="HandleCheck"/> <RadioButton x:name="rb3" Content="Single" HorizontalAlignment="Left" 134

142 Margin="126,134,0,0" VerticalAlignment="Top" GroupName="Status" Width="69" Checked="HandleCheck1"/> <RadioButton x:name="radiobutton" Content="Engaged" HorizontalAlignment="Left" Margin="201,134,0,0" VerticalAlignment="Top" GroupName="Status" Width="89" Checked="HandleCheck1"/> <RadioButton x:name="radiobutton1" Content="Married" GroupName="Status" HorizontalAlignment="Left" Margin="302,134,0,0" VerticalAlignment="Top" Width="95" Checked="HandleCheck1"/> <TextBlock x:name="textblock2" HorizontalAlignment="Left" Margin="386,68,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="191" Height="26"/> <TextBlock x:name="textblock3" HorizontalAlignment="Left" Margin="386,134,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="146" Height="31"/> </Grid> </Window> Here is the implementation in C# for different events. using System.Windows; using System.Windows.Controls; namespace WPFRadioButtonControl /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window public MainWindow() InitializeComponent(); private void HandleCheck1(object sender, RoutedEventArgs e) RadioButton rb = sender as RadioButton; 135

143 textblock3.text = "You are " + rb.content; private void HandleCheck(object sender, RoutedEventArgs e) RadioButton rb = sender as RadioButton; textblock2.text = "You are " + rb.content; When you compile and execute the above code, it will produce the following window. We recommend that you execute the above example code and try the other properties and events of RadioButton. 136

144 26. SCROLLVIEWER WPF A ScrollViewer is a control that provides a scrollable area that can contain other visible elements. The hierarchical inheritance of ScrollViewer class is as follows: Commonly Used Properties of ScrollViewer Class Sr. No. Property & Description 1 ComputedHorizontalScrollBarVisibility Gets a value that indicates whether the horizontal ScrollBar is visible. 2 ComputedHorizontalScrollBarVisibilityProperty Identifies the ComputedHorizontalScrollBarVisibility dependency property. 3 HorizontalScrollBarVisibility Gets or sets a value that indicates whether a horizontal ScrollBar should be displayed. 4 HorizontalScrollBarVisibilityProperty Identifies the HorizontalScrollBarVisibility dependency property. 137

145 HorizontalScrollMode 5 Gets or sets a value that determines how manipulation input influences scrolling behavior on the horizontal axis. HorizontalScrollModeProperty 6 Identifies the HorizontalScrollMode dependency property. HorizontalSnapPointsAlignment 7 Gets or sets a value that indicates how the existing snap points are horizontally aligned versus the initial viewport. 8 HorizontalSnapPointsAlignmentProperty Identifies the HorizontalSnapPointsAlignment dependency property. 9 IsHorizontalScrollChainingEnabled Gets or sets a value that indicates whether scroll chaining is enabled from this child to its parent, for the horizontal axis. 10 IsHorizontalScrollChainingEnabledProperty Identifies the IsHorizontalScrollChainingEnabled dependency property. 11 IsScrollInertiaEnabled Gets or sets a value that indicates whether scroll actions should include inertia in their behavior and value. 12 IsScrollInertiaEnabledProperty Identifies the IsScrollInertiaEnabled dependency property. IsVerticalScrollChainingEnabled 13 Gets or sets a value that indicates whether scroll chaining is enabled from this child to its parent, for the vertical axis. 14 IsVerticalScrollChainingEnabledProperty Identifies the IsVerticalScrollChainingEnabled dependency property. ScrollableHeight 15 Gets a value that represents the vertical size of the area that can be scrolled; the difference between the width of the extent and the width of the viewport. 16 ScrollableHeightProperty Identifies the ScrollableHeight dependency property. ScrollableWidth 17 Gets a value that represents the horizontal size of the area that can be scrolled; the difference between the width of the extent and the width of the viewport. 18 ScrollableWidthProperty Identifies the ScrollableWidth dependency property. VerticalScrollBarVisibility 19 Gets or sets a value that indicates whether a vertical ScrollBar should be displayed. 20 VerticalScrollBarVisibilityProperty Identifies the VerticalScrollBarVisibility dependency property. 21 VerticalScrollMode Gets or sets a value that determines how manipulation input influences scrolling behavior on the vertical axis. 22 VerticalScrollModeProperty Identifies the VerticalScrollMode dependency property. Commonly Used Events of ScrollViewer Class Sr. No. Event & Description 1 DirectManipulationCompleted Occurs when any direct manipulation of the ScrollViewer finishes. 2 DirectManipulationStarted Occurs when any direct manipulation of the ScrollViewer begins. 138

146 3 4 ViewChanged Occurs when manipulations such as scrolling and zooming have caused the view to change. ViewChanging Occurs when manipulations such as scrolling and zooming cause the view to change. Commonly Used Methods of ScrollViewer Class Sr. No Method & Description GetHorizontalScrollBarVisibility Gets the value of the HorizontalScrollBarVisibility dependency property / ScrollViewer.HorizontalScrollBarVisibility XAML attached property from a specified element. GetHorizontalScrollMode Gets the value of the HorizontalScrollMode dependency property / ScrollViewer.HorizontalScrollMode XAML attached property from a specified element. GetIsDeferredScrollingEnabled Gets the value of the IsDeferredScrollingEnabled dependency property / ScrollViewer.IsDeferredScrollingInertiaEnabled XAML attached property from a specified element. GetIsHorizontalScrollChainingEnabled Gets the value of the IsHorizontalScrollChainingEnabled dependency property / ScrollViewer.IsHorizontalScrollChainingEnabled XAML attached property from a specified element. GetIsScrollInertiaEnabled Gets the value of the IsScrollInertiaEnabled dependency property / ScrollViewer.IsScrollInertiaEnabled XAML attached property from a specified element. GetIsVerticalScrollChainingEnabled Gets the value of the IsVerticalScrollChainingEnabled dependency property / ScrollViewer.IsVerticalScrollChainingEnabled XAML attached property from a specified element. GetVerticalScrollBarVisibility Gets the value of the VerticalScrollBarVisibility dependency property / ScrollViewer.VerticalScrollBarVisibility XAML attached property from a specified element. GetVerticalScrollMode Gets the value of the VerticalScrollMode dependency property / ScrollViewer.VerticalScrollMode XAML attached property from a specified element. InvalidateScrollInfo Called when the value of properties that describe the size and location of the scroll area change. ScrollToHorizontalOffset Scrolls the content that is within the ScrollViewer to the specified horizontal offset position. ScrollToVerticalOffset Scrolls the content that is within the ScrollViewer to the specified vertical offset position. SetHorizontalScrollBarVisibility Sets the value of the HorizontalScrollBarVisibility dependency property / ScrollViewer.HorizontalScrollBarVisibility XAML attached property on a specified element. 139

147 SetHorizontalScrollMode Sets the value of the HorizontalScrollMode dependency property / ScrollViewer.HorizontalScrollMode XAML attached property on a specified element. SetIsDeferredScrollingEnabled Sets the value of the IsDeferredScrollingEnabled dependency property / ScrollViewer.IsDeferredScrollingEnabled XAML attached property on a specified element. SetIsHorizontalScrollChainingEnabled Sets the value of the IsHorizontalScrollChainingEnabled dependency property / ScrollViewer.IsHorizontalScrollChainingEnabled XAML attached property on a specified element. SetIsScrollInertiaEnabled Sets the value of the IsScrollInertiaEnabled dependency property / ScrollViewer.IsScrollInertiaEnabled XAML attached property on a specified element. SetIsVerticalScrollChainingEnabled Sets the value of the IsVerticalScrollChainingEnabled dependency property / ScrollViewer.IsVerticalScrollChainingEnabled XAML attached property on a specified element. SetVerticalScrollBarVisibility Sets the value of the VerticalScrollBarVisibility dependency property / ScrollViewer.VerticalScrollBarVisibility XAML attached property on a specified element. SetVerticalScrollMode Sets the value of the VerticalScrollMode dependency property / ScrollViewer.VerticalScrollMode XAML attached property on a specified element. Example 1. Let s create a new WPF project with the name WPFScrollViewerControl. 2. The following example shows how to add a ScrollViewer in your XAML application. 3. We will add two Text Boxes and one with a ScrollViewer and initialize them with some properties and events. <Window x:class="wpfscrollviewercontrol.mainwindow" <Grid> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfscrollviewercontrol" mc:ignorable="d" Title="MainWindow" Height="420" Width="604"> <StackPanel> <!-- A large TextBlock. --> 140

148 <TextBlock Width="300" TextWrapping="Wrap" Margin="0,0,0,30" Text="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac mi ipsum. Phasellus vel malesuada mauris. Donec pharetra, enim sit amet mattis tincidunt, felis nisi semper lectus, vel porta diam nisi in augue. Pellentesque lacus tortor, aliquam et faucibus id, rhoncus ut justo. Sed id lectus odio, eget pulvinar diam. Suspendisse eleifend ornare libero, in luctus purus aliquet non. Sed interdum, sem vitae rutrum rhoncus, felis ligula ultrices sem, in eleifend eros ante id neque." /> <!-- The same large TextBlock, wrapped in a ScrollViewer. --> <ScrollViewer Height="200" Width="200" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto"> <TextBlock Width="300" TextWrapping="Wrap" Text=" This license governs use of code marked as sample or example available on this web site without a license agreement, as provided under the section above titled NOTICE SPECIFIC TO SOFTWARE AVAILABLE ON THIS WEB SITE. If you use such code (the software), you accept this license. If you do not accept the license, do not use the software.lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac mi ipsum. Phasellus vel malesuada mauris. Donec pharetra, enim sit amet mattis tincidunt, felis nisi semper lectus, vel porta diam nisi in augue. Pellentesque lacus tortor, aliquam et faucibus id, rhoncus ut justo. Sed id lectus odio, eget pulvinar diam. Suspendisse eleifend ornare libero, in luctus purus aliquet non. Sed interdum, sem vitae rutrum rhoncus, felis ligula ultrices sem, in eleifend eros ante id neque." /> </Grid> </Window> </ScrollViewer> </StackPanel> When you compile and execute the above code, it will produce the following output: 141

149 We recommend that you execute the above example code and try some of the other properties and events of ScrollViewer class. 142

150 27. SLIDER WPF A slider is a control with the help of which a user can select from a range of values by moving a Thumb control along a track. The hierarchical inheritance of Slider class is as follows: Commonly Used Properties of Slider Sr. No. Property & Description 1 Header Gets or sets the content for the control's header. 2 HeaderProperty Identifies the Header dependency property. 3 HeaderTemplate Gets or sets the DataTemplate used to display the content of the control's header. 4 HeaderTemplateProperty Identifies the HeaderTemplate dependency property. IntermediateValue 5 Gets or sets the value of the Slider while the user is interacting with it, before the value is snapped to either the tick or step value. The value the Slider snaps to is specified by the SnapsTo property. 143

151 6 IntermediateValueProperty Identifies the IntermediateValue dependency property. 7 IsDirectionReversed Gets or sets a value that indicates the direction of increasing value. 8 IsDirectionReversedProperty Identifies the IsDirectionReversed dependency property. 9 IsThumbToolTipEnabled Gets or sets a value that determines whether the slider value is shown in a tool tip for the Thumb component of the Slider. 10 IsThumbToolTipEnabledProperty Identifies the IsThumbToolTipEnabled dependency property. 11 Orientation Gets or sets the orientation of a Slider. 12 OrientationProperty Identifies the Orientation dependency property. 13 StepFrequency Gets or sets the value part of a value range that steps should be created for. 14 StepFrequencyProperty Identifies the StepFrequency dependency property. 15 ThumbToolTipValueConverter Gets or sets the converter logic that converts the range value of the Slider into tool tip content. 16 ThumbToolTipValueConverterProperty Identifies the ThumbToolTipValueConverter dependency property. 17 TickFrequency Gets or sets the increment of the value range that ticks should be created for. 18 TickFrequencyProperty Identifies the TickFrequency dependency property. 19 TickPlacement Gets or sets a value that indicates where to draw tick marks in relation to the track. 20 TickPlacementProperty Identifies the TickPlacement dependency property. Commonly Used Events in Slider Class Sr. No. Event & Description 1 ManipulationCompleted Occurs when a manipulation on the UIElement is complete. (Inherited from UIElement) 2 ManipulationDelta Occurs when the input device changes position during a manipulation. (Inherited from UIElement) 3 ManipulationInertiaStarting Occurs when the input device loses contact with the UIElement object during a manipulation and inertia begins. (Inherited from UIElement) 4 ManipulationStarted Occurs when an input device begins a manipulation on the UIElement. (Inherited from UIElement) 5 ManipulationStarting Occurs when the manipulation processor is first created. (Inherited from UIElement) 6 ValueChanged Occurs when the range value changes. (Inherited from RangeBase) 144

152 Commonly Used Methods in Slider Class Sr. No Method & Description OnManipulationCompleted Called before the ManipulationCompleted event occurs. (Inherited from Control) OnManipulationDelta Called before the ManipulationDelta event occurs. (Inherited from Control) OnManipulationInertiaStarting Called before the ManipulationInertiaStarting event occurs. (Inherited from Control) OnManipulationStarted Called before the ManipulationStarted event occurs. (Inherited from Control) OnManipulationStarting Called before the ManipulationStarting event occurs. (Inherited from Control) OnMaximumChanged Called when the Maximum property changes. (Inherited from RangeBase) OnMinimumChanged Called when the Minimum property changes. (Inherited from RangeBase) OnValueChanged Fires the ValueChanged routed event. (Inherited from RangeBase) SetBinding Attaches a binding to a FrameworkElement, using the provided binding object. (Inherited from FrameworkElement) SetValue Sets the local value of a dependency property on a DependencyObject. (Inherited from DependencyObject) Example 1. Let s create a new WPF project with the name WPFDialog. 2. Drag one slider and two text blocks from the Toolbox. 3. Change the background color from the properties window. 4. The following example shows the usage of Slider in an XAML application. The following XAML code creates a Slider and text blocks and initializes them with some properties and events. <Window x:class="wpfslidercontrol.mainwindow" xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfslidercontrol" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <StackPanel> 145

153 <TextBlock Text="Slider" Margin="10"/> <Slider x:name="slider2" Minimum="0" Maximum="100" TickFrequency="2" TickPlacement="BottomRight" ValueChanged="slider2_ValueChanged" Margin="10"> <Slider.Background> <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0"> <GradientStop Color="Black" Offset="0"/> <GradientStop Color="#FFF5DCDC" Offset="1"/> </LinearGradientBrush> </Slider.Background> </Slider> <TextBlock x:name="textblock1" Margin="10" Text="Current value: 0" /> </StackPanel> </Window> Here is the implementation in C# for ValueChanged event. using System; using System.Windows; namespace WPFSliderControl public partial class MainWindow : Window public MainWindow() InitializeComponent(); private void slider2_valuechanged(object sender, RoutedPropertyChangedEventArgs<double> e) 146

154 int val = Convert.ToInt32(e.NewValue); string msg = String.Format("Current value: 0", val); this.textblock1.text = msg; When you compile and execute the above code, it will produce the following output: We recommend that you execute the above example code and try the other properties and events of Slider class. 147

155 28. TEXTBLOCK WPF A TextBlock is a lightweight control for displaying small amounts of read-only text. The hierarchical inheritance of TextBlock class is as follows: Commonly Used Properties of TextBlock Class Sr. No. Property & Description 1 ContentEnd Gets a TextPointer object for the end of text content in the TextBlock. 2 ContentStart Gets a TextPointer object for the start of text content in the TextBlock. IsTextSelectionEnabled 3 Gets or sets a value that indicates whether text selection is enabled in the TextBlock, either through user action or calling selection-related API. 4 IsTextSelectionEnabledProperty Identifies the IsTextSelectionEnabled dependency property. 5 LineHeight Gets or sets the height of each line of content. 6 MaxLines Gets or sets the maximum lines of text shown in the TextBlock. 7 SelectedText Gets a text range of selected text. 8 SelectionEnd Gets the end position of the text selected in the TextBlock. 9 SelectionHighlightColor Gets or sets the brush used to highlight the selected text. 148

156 10 SelectionStart Gets the starting position of the text selected in the TextBlock. 11 Text Gets or sets the text contents of a TextBlock. 12 TextAlignment Gets or sets a value that indicates the horizontal alignment of text content. 13 TextTrimming Gets or sets the text trimming behavior to employ when content overflows the content area. 14 TextWrapping Gets or sets how the TextBlock wraps text. Commonly Used Events of TextBlock Class Sr. No. Event & Description ContextMenuOpening 1 Occurs when the system processes an interaction that displays a context menu. 2 SelectionChanged Occurs when the text selection has changed. Commonly Used Methods in TextBlock Class Sr. No. Method & Description 1 Focus Focuses the TextBlock, as if it were a conventionally focusable control. 2 Select Selects a range of text in the TextBlock. 3 SelectAll Selects the entire contents in the TextBlock. Example 1. Let s create a new WPF project with WPFTextBlockControl. 2. Drag a text block from the toolbox. 3. Change the background color of the text block from the properties window. 4. The following example shows the usage of TextBlock in an XAML application. 5. Here is the XAML code in which a TextBlock is created with some properties. <Window x:class="wpftextblockcontrol.mainwindow" xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpftextblockcontrol" mc:ignorable="d" 149

157 <Grid> Title="MainWindow" Height="350" Width="604"> <TextBlock FontFamily="Verdana" > LineStackingStrategy="MaxHeight" LineHeight="10" Width="500" TextWrapping="Wrap" Background="#FFE2B1B1" Margin="48,8,48,10" Use the <Run FontSize="30">LineStackingStrategy</Run> property to determine how a line box is created for each line. A value of <Run FontSize="20">MaxHeight</Run> specifies that the stack height is the smallest value that contains all the inline elements on that line when those elements are properly aligned. A value of <Run FontSize="20">BlockLineHeight</Run> specifies that the stack height is determined by the block element LineHeight property value. </TextBlock> </Grid> </Window> When you compile and execute the above code, it will produce the following output: We recommend that you execute the above example code and try the other properties and events of TextBlock class. 150

158 29. TOGGLEBUTTON WPF A Toggle Button is a control that can switch states, such as CheckBox and RadioButton. The hierarchical inheritance of ToggleButton class is as follows: Commonly Used Properties in ToggleButton Class Sr. No. Property & Description 1 IsChecked Gets or sets whether the ToggleButton is checked. 2 IsCheckedProperty Identifies the IsChecked dependency property. 3 IsThreeState Gets or sets a value that indicates whether the control supports three states. 4 IsThreeStateProperty Identifies the IsThreeState dependency property. 151

159 Commonly Used Events in ToggleButton Class Sr. No. Event & Description 1 Checked Fires when a ToggleButton is checked. 2 Indeterminate Fires when the state of a ToggleButton is switched to the indeterminate state. 3 Unchecked Occurs when a ToggleButton is unchecked. Example 1. Let s create a new WPF project with WPFToggleButtonControl. 2. Drag a text block and a toggle button from the toolbox. 3. Change the background color of the text block from the properties window. 4. The following example shows the usage of ToggleButton in an XAML application. 5. The following XAML code creates a ToggleButton and initializes it with some properties. <Window x:class="wpftogglebuttoncontrol.mainwindow" xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpftogglebuttoncontrol" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <StackPanel> <ToggleButton x:name="tb" <TextBlock x:name="text2" Content="Toggle" Checked="HandleCheck" Unchecked="HandleUnchecked" Margin="20" Width="108" HorizontalAlignment="Center"/> Margin="20" Width="300" HorizontalAlignment="Center" FontSize="24" Background="#FFFDE0E0"/> 152

160 </StackPanel> </Window> Here is the C# implementation of Checked and Unchecked events. using System.Windows; namespace WPFToggleButtonControl /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window public MainWindow() InitializeComponent(); private void HandleCheck(object sender, RoutedEventArgs e) text2.text = "Button is Checked"; private void HandleUnchecked(object sender, RoutedEventArgs e) text2.text = "Button is unchecked."; When you compile and execute the above code, it will produce the following window. When you click the button, it will change the color and update the text block. 153

161 We recommend that you execute the above example code and try the other properties and events of ToggleButton. 154

162 30. TOOLTIP WPF A tooltip is a control that creates a pop-up window that displays information for an element in the GUI. The hierarchical inheritance of ToolTip class is as follows: Commonly Used Properties of ToolTip Class Sr. No. Property & Description 1 IsOpen Gets or sets a value that indicates whether the ToolTip is visible. 2 IsOpenProperty Identifies the IsOpen dependency property. 3 Placement Gets or sets how a ToolTip is positioned in relation to the placement target element. 4 PlacementProperty Identifies the Placement dependency property. PlacementTarget 5 Gets or sets the visual element or control that the tool tip should be positioned in relation to when opened by the ToolTipService. 155

163 6 PlacementTargetProperty Identifies the PlacementTarget dependency property. TemplateSettings 7 Gets an object that provides calculated values that can be referenced as TemplateBinding sources when defining templates for a ToolTip. Commonly Used Events of ToolTip Class Sr. No. Event & Description 1 Closed Occurs when a ToolTip is closed and is no longer visible. 2 Opened Occurs when a ToolTip becomes visible. Example 1. Let s create a new WPF project with the name WPFToolTipControl. 2. Drag two text blocks, two text boxes, and one button from the Toolbox. 3. The following example shows how to use a ToolTip in a WPF application. 4. The following XAML code creates a ToolTip with some properties to display ToolTips on Button and Text boxes. <Window x:class="wpftooltipcontrol.mainwindow" <Grid> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpftooltipcontrol" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <TextBlock x:name="textblock" HorizontalAlignment="Left" Margin="101,75,0,0" TextWrapping="Wrap" Text="User Name" VerticalAlignment="Top"/> <TextBlock x:name="textblock1" HorizontalAlignment="Left" Margin="101,125,0,0" TextWrapping="Wrap" Text="Password" VerticalAlignment="Top"/> <TextBox x:name="textbox" HorizontalAlignment="Left" Height="24" Margin="199,75,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="219" ToolTipService.ToolTip = "Enter User Name"/> 156

164 </Grid> </Window> <PasswordBox x:name="passwordbox" HorizontalAlignment="Left" Margin="199,125,0,0" VerticalAlignment="Top" Width="219" Height="24" ToolTipService.ToolTip = "Enter Password"/> <Button x:name="button" Content="Log in" HorizontalAlignment="Left" Margin="199,189,0,0" VerticalAlignment="Top" Width="75" ToolTipService.ToolTip = "Log in"/> When you compile and execute the above code, it will produce the following output. When the mouse enters the region of the Button or the Text boxes, it will show a tool tip. We recommend that you execute the above example code and try the other properties and events of ToolTip class. 157

165 31. WINDOW WPF Window is the root window of XAML applications which provides minimize/maximize option, title bar, border, and close button. It also provides the ability to create, configure, show, and manage the lifetime of windows and dialog boxes. The hierarchical inheritance of Window class is as follows: Commonly Used Properties of Window Class Sr. No. Property & Description 1 AllowsTransparency Gets or sets a value that indicates whether a window's client area supports transparency. 2 DialogResult Gets or sets the dialog result value, which is the value that is returned from the ShowDialog method. 3 Icon Gets or sets a window's icon. 4 IsActive 158

166 Gets a value that indicates whether the window is active. 5 Left Gets or sets the position of the window's left edge, in relation to the desktop. 6 OwnedWindows Gets a collection of windows for which this window is the owner. 7 Owner Gets or sets the Window that owns this Window. 8 ResizeMode Gets or sets the resize mode. RestoreBounds 9 Gets the size and location of a window before being either minimized or maximized. ShowActivated 10 Gets or sets a value that indicates whether a window is activated when first shown. 11 ShowInTaskbar Gets or sets a value that indicates whether the window has a task bar button. 12 SizeToContent Gets or sets a value that indicates whether a window will automatically size itself to fit the size of its content. 13 TaskbarItemInfo Gets or sets the Windows 7 taskbar thumbnail for the Window. 14 Title Gets or sets a window's title. 15 Top Gets or sets the position of the window's top edge, in relation to the desktop. 16 Topmost Gets or sets a value that indicates whether a window appears in the topmost z-order. 17 WindowStartupLocation Gets or sets the position of the window when first shown. 18 WindowState Gets or sets a value that indicates whether a window is restored, minimized, or maximized. 19 WindowStyle Gets or sets a window's border style. Commonly Used Events of Window Class Sr. No. Event & Description 1 Activated Occurs when a window becomes the foreground window. 2 Closed Occurs when the window is about to close. Closing 3 Occurs directly after Close is called, and can be handled to cancel window closure. 4 ContentRendered Occurs after a window's content has been rendered. 5 Deactivated Occurs when a window becomes a background window. 6 LocationChanged Occurs when the window's location changes. 7 SourceInitialized 159

167 This event is raised to support interoperation with Win32. See HwndSource. 8 StateChanged Occurs when the window's WindowState property changes. Commonly Used Methods of Window Class Sr. No. Method & Description 1 Activate Attempts to bring the window to the foreground and activates it. 2 Close Manually closes a Window. DragMove 3 Allows a window to be dragged by a mouse with its left button down over an exposed area of the window's client area. GetWindow 4 Returns a reference to the Window object that hosts the content tree within which the dependency object is located. 5 Hide Makes a window invisible. Show 6 Opens a window and returns without waiting for the newly opened window to close. 7 ShowDialog Opens a window and returns only when the newly opened window is closed. Example 1. When you create a new WPF project, then by default, the Window control is present. Let s have a look at the following example. 2. The following XAML code starts with a <Window> Tag and ends with a </Window> tag. The code sets some properties for the window and creates some other controls like text blocks, button, etc. <Window x:class="wpftooltipcontrol.mainwindow" <Grid> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpftooltipcontrol" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <TextBlock x:name="textblock" HorizontalAlignment="Left" Margin="101,75,0,0" TextWrapping="Wrap" Text="User Name" VerticalAlignment="Top"/> <TextBlock x:name="textblock1" HorizontalAlignment="Left" 160

168 </Grid> </Window> Margin="101,125,0,0" TextWrapping="Wrap" Text="Password" VerticalAlignment="Top"/> <TextBox x:name="textbox" HorizontalAlignment="Left" Height="24" Margin="199,75,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="219" ToolTipService.ToolTip = "Enter User Name"/> <PasswordBox x:name="passwordbox" HorizontalAlignment="Left" Margin="199,125,0,0" VerticalAlignment="Top" Width="219" Height="24" ToolTipService.ToolTip = "Enter Password"/> <Button x:name="button" Content="Log in" HorizontalAlignment="Left" Margin="199,189,0,0" VerticalAlignment="Top" Width="75" ToolTipService.ToolTip = "Log in"/> When you compile and execute the above code, it will display the following output. When the mouse enters the region of the Button or the Textboxes, it will show a tooltip. We recommend that you execute the above example code and try some other properties and events of this class. 161

169 32. THIRD-PARTY CONTROLS WPF Third-party controls are those which are not created by Microsoft but are created by some individual or company by using WPF User Control or Custom Control. Telerik and DevExpress are the most popular companies for creating third-party controls. In this chapter, we will be using Telerik controls. So let s start by following the steps given below. 1. Go to the link which contains the Telerik WPF controls and download the UI for WPF. 2. Once the download is complete, install the files on your machine. 3. After the installation, open Visual Studio and create a new WPF project with the name WPF3rdPartyControls. 4. On Toolbox, you will see the Telerik UI controls. In addition, you will observe that in solution explorer, all the required dll are also added after installation. 162

170 5. Let s expand the Telerik UI for WPF input 2015 Q2 in the toolbox. You will see many built-in controls. 6. Now drag RadCalculator from toolbox box to the design window. 7. Take a look at your XAML window in which RadCalculator tag has been added. <Window x:class="wpf3rdpartycontrols.mainwindow" xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpf3rdpartycontrols" xmlns:telerik=" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <Grid> 163

171 <telerik:radcalculator HorizontalAlignment="Left" Margin="174,25,0,0" VerticalAlignment="Top"/> </Grid> </Window> 8. Let s compile and execute the above code. You will see a fully functional calculator on your window with just one line of code. 9. That s the beauty of third-party controls. But it is not free, you will need to buy a license if you want to use third-party controls in your application. Let s have a look at another Telerik control. Create a new WPF project with the name WPF3rdPartyControls. Drag the RadDateTimePicker control from the toolbox. The XAML code is as follows: <Window x:class="raddatetimepickerdemo.mainwindow" xmlns=" xmlns:x=" xmlns:telerik=" Title="MainWindow" Height="350" Width="604"> <Grid> <telerik:raddatetimepicker VerticalAlignment="Top" Name="dateTimePicker" /> </Grid> </Window> Here is the C# code in which selection changed event is implemented. 164

172 using System; using System.Windows; using System.Windows.Controls; namespace RadDateTimePickerDemo public partial class MainWindow : Window public MainWindow() InitializeComponent(); datetimepicker.selectionchanged += datetimepicker_selectionchanged; void datetimepicker_selectionchanged( object sender, SelectionChangedEventArgs e ) DateTime? dt = datetimepicker.selectedvalue; DateTime? date = datetimepicker.selecteddate; TimeSpan? time = datetimepicker.selectedtime; MessageBox.Show( "Selected date/time: " + dt.tostring() ); When you compile and execute the above code, it will produce the following window. Select any time and date and it will be displayed on the message box. 165

173 Example Here is an example of RichTextBox. The following XAML code creates three toggle buttons and a rich textbox. <Window x:class="richtextboxdemo.mainwindow" xmlns=" <Grid> xmlns:x=" xmlns:telerik=" Title="MainWindow" Height="350" Width="604"> <StackPanel> <StackPanel Orientation="Horizontal"> <ToggleButton Content="B" x:name="boldbutton" Click="BoldButton_Click"/> <ToggleButton Content="I" x:name="italicbutton" Click="ItalicButton_Click" /> <ToggleButton Content="U"x:Name="UnderlineButton" </StackPanel> Click="UnderlineButton_Click" /> <telerik:radrichtextbox Height="250" Width="400" Name="richTextBox"/> </StackPanel> </Grid> </Window> Here is the implementation in C# for button click event. using System.Windows; namespace RichTextBoxDemo /// <summary> 166

174 /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window public MainWindow() InitializeComponent(); private void BoldButton_Click( object sender, RoutedEventArgs e ) richtextbox.togglebold(); private void ItalicButton_Click( object sender, RoutedEventArgs e ) richtextbox.toggleitalic(); private void UnderlineButton_Click( object sender, RoutedEventArgs e ) richtextbox.toggleunderline(); 167

175 When you compile and execute the above code, it will produce the following window. With the help of the three buttons, you can format the text (bold, italic, underline) typed inside the rich textbox. We recommend that you try to use the other controls available in your toolbox and experiment. 168

176 33. WPF LAYOUTS WPF The layout of controls is very important and critical for application usability. It is used to arrange a group of GUI elements in your application. There are certain important things to consider while selecting layout panels: Positions of the child elements Sizes of the child elements Layering of overlapping child elements on top of each other Fixed pixel arrangement of controls doesn t work when the application is to be sed on different screen resolutions. XAML provides a rich set of built-in layout panels to arrange GUI elements in an appropriate way. Some of the most commonly used and popular layout panels are as follows: Stack Panel Wrap Panel Dock Panel Canvas Panel Grid Panel Stack Panel Stack panel is a simple and useful layout panel in XAML. In stack panel, child elements can be arranged in a single line, either horizontally or vertically, based on the orientation property. It is often used whenever any kind of list is to be created. The hierarchical inheritance of StackPanel class is as follows: 169

177 Commonly Used Properties of StackPanel Sr. No. Property & Description 1 Background Gets or sets a Brush that fills the panel content area. (Inherited from Panel) Children 2 Gets a UIElementCollection of child elements of this Panel. (Inherited from Panel.) Height 3 Gets or sets the suggested height of the element. (Inherited from FrameworkElement.) ItemHeight 4 Gets or sets a value that specifies the height of all items that are contained within a WrapPanel. ItemWidth 5 Gets or sets a value that specifies the width of all items that are contained within a WrapPanel. LogicalChildren 6 Gets an enumerator that can iterate the logical child elements of this Panel element. (Inherited from Panel.) LogicalOrientation 7 The Orientation of the panel, if the panel supports layout in only a single dimension. (Inherited from Panel.) Margin 8 Gets or sets the outer margin of an element. (Inherited from FrameworkElement.) Name 9 Gets or sets the identifying name of the element. The name provides a reference so that code-behind, such as event handler code, can refer to a 170

178 markup element after it is constructed during processing by a XAML processor. (Inherited from FrameworkElement.) Orientation 10 Gets or sets a value that specifies the dimension in which child content is arranged. Parent 11 Gets the logical parent element of this element. (Inherited from FrameworkElement.) Resources 12 Gets or sets the locally-defined resource dictionary. (Inherited from FrameworkElement.) Style 13 Gets or sets the style used by this element when it is rendered. (Inherited from FrameworkElement.) 14 Width Gets or sets the width of the element. (Inherited from FrameworkElement.) Example The following example shows how to add child elements into a StackPanel. The following XAML implementation creates buttons inside a StackPanel with some properties. <Window x:class="wpfstackpanel.mainwindow" <Grid> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfstackpanel" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <StackPanel Orientation="Horizontal"> <Button x:name="button" Content="Button" Margin="10" Width="120" Height="30"/> <Button x:name="button1" Content="Button" Margin="10" Width="120" Height="30"/> <Button x:name="button2" Content="Button" Margin="10" Width="120" Height="30"/> <Button x:name="button3" Content="Button" Margin="10" Width="120" Height="30"/> </StackPanel> </Grid> </Window> 171

179 When you compile and execute the above code, it will produce the following window. You can see that the child elements are arranged in horizontal order. Yan can change the arrangement by setting the orientation property to Horizontal. By default, child elements will be arranged in vertical order. We recommend that you execute the above example code and try the other properties of this class as well. Wrap Panel In WrapPanel, child elements are positioned in sequential order, from left to right or from top to bottom based on the orientation property. The only difference between StackPanel and WrapPanel is that it doesn t stack all the child elements in a single line; it wraps the remaining elements to another line if there is no space left. WrapPanel is mostly used for tabs or menu items. The hierarchical inheritance of WrapPanel class is as follows: 172

180 Commonly Used Properties of WrapPanel Sr. No. Property & Description 1 Background Gets or sets a Brush that fills the panel content area. (Inherited from Panel) Children 2 Gets a UIElementCollection of child elements of this Panel. (Inherited from Panel.) Height 3 Gets or sets the suggested height of the element. (Inherited from FrameworkElement.) ItemHeight 4 Gets or sets a value that specifies the height of all items that are contained within a WrapPanel. ItemWidth 5 Gets or sets a value that specifies the width of all items that are contained within a WrapPanel. LogicalChildren 6 Gets an enumerator that can iterate the logical child elements of this Panel element. (Inherited from Panel.) LogicalOrientation 7 The Orientation of the panel, if the panel supports layout in only a single dimension. (Inherited from Panel.) Margin 8 Gets or sets the outer margin of an element. (Inherited from FrameworkElement.) Name 9 Gets or sets the identifying name of the element. The name provides a reference so that code-behind, such as event handler code, can refer to a 173

181 markup element after it is constructed during processing by a XAML processor. (Inherited from FrameworkElement.) Orientation 10 Gets or sets a value that specifies the dimension in which child content is arranged. Parent 11 Gets the logical parent element of this element. (Inherited from FrameworkElement.) Resources 12 Gets or sets the locally-defined resource dictionary. (Inherited from FrameworkElement.) Style 13 Gets or sets the style used by this element when it is rendered. (Inherited from FrameworkElement.) 14 Width Gets or sets the width of the element. (Inherited from FrameworkElement.) Example The following example shows how to add child elements into a WrapPanel. Here is the XAML implementation in which Text Blocks and Text Boxes are created inside a WrapPanel in horizontal direction. <Window x:class="wpfwrappanel.mainwindow" <Grid> </Grid> </Window> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfwrappanel" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <WrapPanel Orientation="Vertical"> <TextBlock Text="Fist Name" Width="60" Height="20" Margin="5"/> <TextBox Width="200" Height="20" Margin="5"/> <TextBlock Text="Last Name" Width="60" Height="20" Margin="5"/> <TextBox Width="200" Height="20" Margin="5"/> <TextBlock Text="Age" Width="60" Height="20" Margin="5"/> <TextBox Width="60" Height="20" Margin="5"/> <TextBlock Text="Title" Width="60" Height="20" Margin="5"/> <TextBox Width="200" Height="20" Margin="5"/> </WrapPanel> 174

182 When you compile and execute the above code, it will produce the following window. You can change the arrangement from top to bottom by changing the orientation property to Vertical. We recommend that you execute the above example code and try the other properties of this class as well. Dock Panel DockPanel defines an area to arrange child elements relative to each other, either horizontally or vertically. With DockPanel you can easily dock child elements to top, bottom, right, left and center using the Dock property. With LastChildFill property, the last child element fill the remaining space regardless of any other dock value when set for that element. The hierarchical inheritance of DockPanel class is as follows: 175

183 Commonly Used Properties of DockPanel Sr. No. Property & Description 1 Background Gets or sets a Brush that fills the panel content area. (Inherited from Panel) Children 2 Gets a UIElementCollection of child elements of this Panel. (Inherited from Panel.) Dock 3 Gets or sets a value that indicates the position of a child element within a parent DockPanel. Height 4 Gets or sets the suggested height of the element. (Inherited from FrameworkElement.) ItemHeight 5 Gets or sets a value that specifies the height of all items that are contained within a WrapPanel. ItemWidth 6 Gets or sets a value that specifies the width of all items that are contained within a WrapPanel. LastChildFill 7 Gets or sets a value that indicates whether the last child element within a DockPanel stretches to fill the remaining available space. LogicalChildren 8 Gets an enumerator that can iterate the logical child elements of this Panel element. (Inherited from Panel.) LogicalOrientation 9 The Orientation of the panel, if the panel supports layout in only a single dimension. (Inherited from Panel.) 176

184 10 Margin Gets or sets the outer margin of an element. (Inherited from FrameworkElement.) Name 11 Gets or sets the identifying name of the element. The name provides a reference so that code-behind, such as event handler code, can refer to a markup element after it is constructed during processing by a XAML processor. (Inherited from FrameworkElement.) Orientation 12 Gets or sets a value that specifies the dimension in which child content is arranged. Parent 13 Gets the logical parent element of this element. (Inherited from FrameworkElement.) Resources 14 Gets or sets the locally-defined resource dictionary. (Inherited from FrameworkElement.) Style 15 Gets or sets the style used by this element when it is rendered. (Inherited from FrameworkElement.) 16 Width Gets or sets the width of the element. (Inherited from FrameworkElement.) Commonly Used Methods of DockPanel Sr. Method & Description No. 1 GetDock Gets the value of the Dock attached property for a specified UIElement. 2 SetDock Sets the value of the Dock attached property to a specified element. Example The following example shows how to add child elements into a DockPanel. The following XAML implementation creates buttons inside a DockPanel. <Window x:class="wpfdockpanel.mainwindow" <Grid> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfdockpanel" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <DockPanel LastChildFill="True"> <Button Content="Top" DockPanel.Dock="Top" Click="Click_Me"/> <Button Content="Bottom" DockPanel.Dock="Bottom" Click="Click_Me"/> 177

185 <Button Content="Left" Click="Click_Me"/> <Button Content="Right" DockPanel.Dock="Right" Click="Click_Me"/> <Button Content="Center" Click="Click_Me"/> </DockPanel> </Grid> </Window> Here is the implementation in C# for event. using System.Windows; using System.Windows.Controls; namespace WPFDockPanel /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window public MainWindow() InitializeComponent(); private void Click_Me(object sender, RoutedEventArgs e) Button btn = sender as Button; string str = btn.content.tostring() + " button clicked"; MessageBox.Show(str); 178

186 When you compile and execute the above code, it will display the following output: On clicking any button, it will also display a message. For example, when you click the button which is at the Center, it will display the following message. We recommend that you execute the above example code and try its other properties as well. Canvas Panel Canvas panel is the basic layout panel in which the child elements can be positioned explicitly using coordinates that are relative to the Canvas any side such as left, right, top and bottom. Typically, a Canvas is used for 2D graphic elements (such as Ellipse, Rectangle etc.), but not for UI elements because specifying absolute coordinates create trouble while resizing, localizing or scaling your XAML application. The hierarchical inheritance of Canvas class is as follows: 179

187 Commonly Used Properties of Canvas Class Sr. No. Property & Description 1 Background Gets or sets a Brush that fills the panel content area. (Inherited from Panel) 2 Children Gets a UIElementCollection of child elements of this Panel. (Inherited from Panel.) 3 Height Gets or sets the suggested height of the element. (Inherited from FrameworkElement.) 4 ItemHeight Gets or sets a value that specifies the height of all items that are contained within a WrapPanel. 5 ItemWidth Gets or sets a value that specifies the width of all items that are contained within a WrapPanel. 6 LogicalChildren Gets an enumerator that can iterate the logical child elements of this Panel element. (Inherited from Panel.) 7 LogicalOrientation The Orientation of the panel, if the panel supports layout in only a single dimension. (Inherited from Panel.) 8 LeftProperty Identifies the Canvas.Left XAML attached property. Margin 9 Gets or sets the outer margin of an element. (Inherited from FrameworkElement.) 180

188 Name 10 Gets or sets the identifying name of the element. The name provides a reference so that code-behind, such as event handler code, can refer to a markup element after it is constructed during processing by a XAML processor. (Inherited from FrameworkElement.) Orientation 11 Gets or sets a value that specifies the dimension in which child content is arranged. Parent 12 Gets the logical parent element of this element. (Inherited from FrameworkElement.) Resources 13 Gets or sets the locally-defined resource dictionary. (Inherited from FrameworkElement.) Style 14 Gets or sets the style used by this element when it is rendered. (Inherited from FrameworkElement.) 15 TopProperty Identifies the Canvas.Top XAML attached property. 16 Width Gets or sets the width of the element. (Inherited from FrameworkElement.) 17 ZIndexProperty Identifies the Canvas.ZIndex XAML attached property. Commonly Used Methods of Canvas Sr. Method & Description No. GetLeft 1 Gets the value of the Canvas.Left XAML attached property for the target element. GetTop 2 Gets the value of the Canvas.Top XAML attached property for the target element. GetZIndex 3 Gets the value of the Canvas.ZIndex XAML attached property for the target element. SetLeft 4 Sets the value of the Canvas.Left XAML attached property for a target element. 5 SetTop Sets the value of the Canvas.Top XAML attached property for a target element. SetZIndex 6 Sets the value of the Canvas.ZIndex XAML attached property for a target element. Example The following example shows how to add child elements into a Canvas. The following XAML implementation creates ellipses inside a Canvas with different offset properties. <Window x:class="wpfconvas.mainwindow" xmlns=" xmlns:x=" 181

189 xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfconvas" mc:ignorable="d" Title="MainWindow" Height="400" Width="604"> <Grid> <Canvas Width="580" Height="360" > <Ellipse Canvas.Left="30" Canvas.Top="30" Fill="Gray" Width="200" Height="120" /> <Ellipse Canvas.Right="30" Canvas.Top="30" Fill="Aqua" Width="200" Height="120" /> <Ellipse Canvas.Left="30" Canvas.Bottom="30" Fill="Gainsboro" Width="200" Height="120" /> <Ellipse Canvas.Right="30" Canvas.Bottom="30" Fill="LightCyan" Width="200" Height="120"/> </Canvas> </Grid> </Window> When you compile and execute the above code, it will produce the following output: We recommend that you execute the above example code and try the other properties of this class as well. 182

190 Grid Panel A Grid Panel provides a flexible area which consists of rows and columns. In a Grid, child elements can be arranged in tabular form. Elements can be added to any specific row and column by using Grid.Row and Grid.Column properties. By default, a Grid panel is created with one row and one column. Multiple rows and columns are created by RowDefinitions and ColumnDefinitions properties. The height of rows and the width of columns can be defined in the following three ways: Fixed value: To assign a fixed size of logical units (1/96 inch) Auto: It will take space which are required for the controls in that specific row/column. Star (*): It will take the remaining space when Auto and fixed sized are filled. The hierarchical inheritance of Canvas class is as follows. Commonly Used Properties of Grid Class Sr. No. Property & Description 1 Background Gets or sets a Brush that fills the panel content area. (Inherited from Panel) 2 Children Gets a UIElementCollection of child elements of this Panel. (Inherited from Panel.) 3 ColumnDefinitions Gets a list of ColumnDefinition objects defined on this instance of Grid. 183

191 Height 4 Gets or sets the suggested height of the element. (Inherited from FrameworkElement.) ItemHeight 5 Gets or sets a value that specifies the height of all items that are contained within a WrapPanel. ItemWidth 6 Gets or sets a value that specifies the width of all items that are contained within a WrapPanel. Margin 7 Gets or sets the outer margin of an element. (Inherited from FrameworkElement.) Name 8 Gets or sets the identifying name of the element. The name provides a reference so that code-behind, such as event handler code, can refer to a markup element after it is constructed during processing by a XAML processor. (Inherited from FrameworkElement.) Orientation 9 Gets or sets a value that specifies the dimension in which child content is arranged. Parent 10 Gets the logical parent element of this element. (Inherited from FrameworkElement.) 11 Resources Gets or sets the locally-defined resource dictionary. (Inherited from FrameworkElement.) 12 RowDefinitions Gets a list of RowDefinition objects defined on this instance of Grid. Style 13 Gets or sets the style used by this element when it is rendered. (Inherited from FrameworkElement.) 14 Width Gets or sets the width of the element. (Inherited from FrameworkElement.) Commonly Used Properties of Grid Class Sr. No Method & Description GetColumn Gets the value of the Grid.Column XAML attached property from the specified FrameworkElement. GetColumnSpan Gets the value of the Grid.ColumnSpan XAML attached property from the specified FrameworkElement. GetRow Gets the value of the Grid.Row XAML attached property from the specified FrameworkElement. SetColumn Sets the value of the Grid.Column XAML attached property on the specified FrameworkElement. SetRow Sets the value of the Grid.Row XAML attached property on the specified FrameworkElement. SetRowSpan Sets the value of the Grid.RowSpan XAML attached property on the specified FrameworkElement. 184

192 Example The following example shows how to add child elements into a Grid to specify it in a tabular form. In the following XAML implementation, Text Blocks are added in the first column and Text Boxes are added in the second column of the Grid. <Window x:class="wpfgrid.mainwindow" xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfgrid" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <Grid x:name="formlayoutgrid" Background="AliceBlue"> </Grid> </Window> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="*" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <TextBlock Grid.Row="0" Grid.Column="0" Text="Name" Margin="10" HorizontalAlignment="Left" VerticalAlignment="Center" Width="100"/> <TextBox Grid.Row="0" Grid.Column="1" Margin="10" /> <TextBlock Grid.Row="1" Grid.Column="0" Text="ID" Margin="10" HorizontalAlignment="Left" VerticalAlignment="Center" Width="100"/> <TextBox Grid.Row="1" Grid.Column="1" Margin="10" /> <TextBlock Grid.Row="2" Grid.Column="0" Text="Age" Margin="10" HorizontalAlignment="Left" VerticalAlignment="Center" Width="100"/> <TextBox Grid.Row="2" Grid.Column="1" Margin="10" /> 185

193 When you compile and execute the above code, it will produce the following window. We recommend that you execute the above example code and try some of the other properties of this class as well. 186

194 34. NESTING OF LAYOUT WPF Nesting of layout means the use layout panel inside another layout, e.g. define stack panels inside a grid. This concept is widely used to take the advantages of multiple layouts in an application. In the following example, we will be using stack panels inside a grid. Let s have a look at the following XAML code. <Window x:class="wpfnestinglayouts.mainwindow" xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfnestinglayouts" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <Grid Background="AntiqueWhite"> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Label Content="Employee Info" FontSize="15" FontWeight="Bold" Grid.Column="0" Grid.Row="0"/> <StackPanel Grid.Column="0" Grid.Row="1" Orientation="Horizontal"> <Label Content="Name" VerticalAlignment="Center" Width="70"/> <TextBox Name="txtName" Text="Muhammad Ali" VerticalAlignment="Center" Width="200"></TextBox> </StackPanel> 187

195 <StackPanel Grid.Column="0" Grid.Row="2" Orientation="Horizontal"> <Label Content="ID" VerticalAlignment="Center" Width="70"/> <TextBox Name="txtCity" Text="421" VerticalAlignment="Center" Width="50"></TextBox> </StackPanel> <StackPanel Grid.Column="0" Grid.Row="3" Orientation="Horizontal"> <Label Content="Age" VerticalAlignment="Center" Width="70"/> <TextBox Name="txtState" Text="32" VerticalAlignment="Center" Width="50"></TextBox> </StackPanel> <StackPanel Grid.Column="0" Grid.Row="4" Orientation="Horizontal"> <Label Content="Title" VerticalAlignment="Center" Width="70"/> <TextBox Name="txtCountry" Text="Programmer" VerticalAlignment="Center" Width="200"></TextBox> </Grid> </Window> </StackPanel> When you compile and execute the above code, it will produce the following window. We recommend that you execute the above example code and try other nesting layouts. 188

196 35. WPF INPUT WPF Windows Presentation Foundation (WPF) provides a powerful API with the help of which applications can get input from various devices such as mouse, keyboard, and touch panels. In this chapter, we will discuss the following types of input which can be handled in WPF applications: Mouse Keyboard ContextMenu or RoutedCommands Multi Touch Mouse There are different types of mouse inputs such as MouseDown, MouseEnter, MouseLeave, etc. In the following example, we will handle some of the mouse inputs. 1. Let s create a new WPF project with the name WPFMouseInput. 2. Drag a rectangle and three Text blocks to a stack panel and set the following properties and events as shown in the following XAML file. <Window x:class="wpfmouseinput.mainwindow" xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfmouseinput" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <StackPanel> <Rectangle x:name="mrrec" Fill="AliceBlue" </Rectangle> MouseEnter="OnMouseEnter" MouseLeave="OnMouseLeave" MouseMove="OnMouseMove" MouseDown="OnMouseDown" Height="100" Margin="20"> <TextBlock x:name="txt1" Height="31" HorizontalAlignment="Right" 189

197 Width="250" Margin="0,0,294,0" /> <TextBlock x:name="txt2" Height="31" HorizontalAlignment="Right" Width="250" Margin="0,0,294,0" /> <TextBlock x:name="txt3" Height="31" HorizontalAlignment="Right" Width="250" Margin="0,0,294,0" /> </StackPanel> </Window> Here is the C# code in which different mouse events are handled. using System.Windows; using System.Windows.Input; using System.Windows.Media; using System.Windows.Shapes; namespace WPFMouseInput public partial class MainWindow : Window public MainWindow() InitializeComponent(); private void OneMouseEnter(object sender, MouseEventArgs e) Rectangle source = e.source as Rectangle; if (source!= null) source.fill = Brushes.SlateGray; txt1.text = "Mouse Entered"; private void OnMouseLeave(object sender, MouseEventArgs e) // Cast the source of the event to a Button. Rectangle source = e.source as Rectangle; 190

198 // If source is a Button. if (source!= null) source.fill = Brushes.AliceBlue; txt1.text = "Mouse Leave"; txt2.text = ""; txt3.text = ""; private void OnMouseMove(object sender, MouseEventArgs e) Point pnt = e.getposition(mrrec); txt2.text = "Mouse Move: " + pnt.tostring(); private void OnMouseDown(object sender, MouseButtonEventArgs e) Rectangle source = e.source as Rectangle; Point pnt = e.getposition(mrrec); txt3.text = "Mouse Click: " + pnt.tostring(); if (source!= null) source.fill = Brushes.Beige; When you compile and execute the above code, it will produce the following window: 191

199 When the mouse enters inside the rectangle, the color of the rectangle will automatically change. In addition, you will get a message that the mouse has entered along with its coordinates. When you click inside the rectangle, it will change color and show the coordinates at which mouse has been clicked. 192

200 When the mouse leaves the rectangle, it will show a message that mouse has left and the rectangle will change to its default color. Keyboard There are many types of keyboard inputs such as KeyDown, KeyUp, TextInput, etc. In the following example, some of the keyboard inputs are handled. The following example defines a handler for the Click event and a handler for the KeyDown event. 1. Let s create a new WPF project with the name WPFKeyboardInput. 2. Drag a textbox and a button to a stack panel and set the following properties and events as shown in the following XAML file. <Window x:class="wpfkeyboardinput.mainwindow" <Grid> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfkeyboardinput" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <StackPanel Orientation="Horizontal" KeyDown="OnTextInputKeyDown"> <TextBox Width="400" Height="30" Margin="10"/> <Button Click="OnTextInputButtonClick" 193

201 Content="Open" Margin="10" Width="50" Height="30"/> </StackPanel> </Grid> </Window> Here is the C# code in which different keyboard and click events are handled. using System.Windows; using System.Windows.Input; namespace WPFKeyboardInput /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window public MainWindow() InitializeComponent(); private void OnTextInputKeyDown(object sender, KeyEventArgs e) if (e.key == Key.O && Keyboard.Modifiers == ModifierKeys.Control) handle(); e.handled = true; private void OnTextInputButtonClick(object sender, RoutedEventArgs e) handle(); e.handled = true; public void handle() MessageBox.Show("Do you want to open a file?"); 194

202 When the above code is compiled and executed, it will produce the following window: If you click the Open button or press CTRL+O keys inside textbox, it will display the same message. ContextMenu or RoutedCommands RoutedCommands enable input handling at a more semantic level. These are actually simple instructions as New, Open, Copy, Cut, and Save. These commands are very useful and they can be accessed from a Menu or from a keyboard shortcut. It disables the controls if the command becomes unavailable. The following example defines the commands for Menu items. 1. Let s create a new WPF project with the name WPFCommandsInput. 195

203 2. Drag a menu control to a stack panel and set the following properties and commands as shown in the following XAML file. <Window x:class="wpfcontextmenu.mainwindow" <Grid> </Grid> </Window> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfcontextmenu" mc:ignorable="d" Title="MainWindow" Height="350" Width="525"> <StackPanel x:name="stack" Background="Transparent"> <StackPanel.ContextMenu> <ContextMenu> <MenuItem Header="New" Command="New" /> <MenuItem Header="Open" Command="Open" /> <MenuItem Header="Save" Command="Save" /> </ContextMenu> </StackPanel.ContextMenu> <Menu> </Menu> </StackPanel> <MenuItem Header="File" > <MenuItem Header="New" Command="New" /> <MenuItem Header="Open" Command="Open" /> <MenuItem Header="Save" Command="Save" /> </MenuItem> Here is the C# code in which different commands are handled. using System.Windows; using System.Windows.Input; namespace WPFContextMenu 196

204 /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window public MainWindow() InitializeComponent(); CommandBindings.Add(new CommandBinding(ApplicationCommands.New, NewExecuted, CanNew)); CommandBindings.Add(new CommandBinding(ApplicationCommands.Open, OpenExecuted, CanOpen)); CommandBindings.Add(new CommandBinding(ApplicationCommands.Save, SaveExecuted, CanSave)); private void NewExecuted(object sender, ExecutedRoutedEventArgs e) MessageBox.Show("You want to create new file."); private void CanNew(object sender, CanExecuteRoutedEventArgs e) e.canexecute = true; private void OpenExecuted(object sender, ExecutedRoutedEventArgs e) MessageBox.Show("You want to open existing file."); private void CanOpen(object sender, CanExecuteRoutedEventArgs e) e.canexecute = true; private void SaveExecuted(object sender, ExecutedRoutedEventArgs e) MessageBox.Show("You want to save a file."); 197

205 private void CanSave(object sender, CanExecuteRoutedEventArgs e) e.canexecute = true; When the above code is compiled and executed, it will produce the following window: Now you can access this menu items, either from the menu or from the shortcut keys commands. From either option, it will execute the commands. Multi Touch Windows 7 and its higher versions have the ability to receive input from multiple touchsensitive devices. WPF applications can also handle touch input as other input, such as the mouse or keyboard, by raising events when a touch occurs. WPF exposes two types of events when a touch occurs: touch events and manipulation events. Touch events provide raw data about each finger on a touchscreen and its movement. Manipulation events interpret the input as certain actions. Both types of events are discussed in this section. The following components are required to develop an application that can respond to touch. Microsoft Visual Studio 2010 or later versions. Windows 7 or higher version. A device, such as a touchscreen, that supports Windows Touch. The following terms are commonly used when touch input is discussed: 198

206 Touch: Type of user input which can be recognized in Windows 7 or later. Touch input is initiated from a touch-sensitive screen. Multi Touch: Type of input which occurs from more than one point simultaneously. In WPF, when touch is discussed, it usually means multi-touch. Manipulation: Occurs when touch is inferred as a physical action that is applied to an object. In WPF, manipulation events interpret input as a translation, expansion, or rotation manipulation. Touch Device: Represents a device that produces touch input, such as a single finger on a touchscreen. Example To understand all these concepts, let s create a new WPF project with the name WPFTouchInput. 1. Drag a Rectangle from a toolbox to the design window and fill the rectangle with an image or any color. If you want to use an image, then don t forget to include the image in your solution, otherwise the program will not execute. 2. The following XAML code initializes a rectangle with different properties and events. <Window x:class="wpfmultitouchinput.mainwindow" xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfmultitouchinput" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <Window.Resources> <MatrixTransform x:key="initialmatrixtransform"> <MatrixTransform.Matrix> <Matrix OffsetX="200" OffsetY="200"/> </MatrixTransform.Matrix> </MatrixTransform> </Window.Resources> <Canvas> <Rectangle Name="manRect" Width="321" Height="241" RenderTransform="StaticResource InitialMatrixTransform" IsManipulationEnabled="true" Canvas.Left="-70" Canvas.Top="-170"> 199

207 <Rectangle.Fill> <ImageBrush ImageSource="Images/DSC_0076.JPG"/> </Rectangle.Fill> </Rectangle> </Canvas> </Window> Here is the implementation for different manipulation events: using System.Windows; using System.Windows.Input; using System.Windows.Media; using System.Windows.Shapes; namespace WPFMultiTouchInput public partial class MainWindow : Window public MainWindow() InitializeComponent(); void Window_ManipulationStarting(object sender, ManipulationStartingEventArgs e) e.manipulationcontainer = this; e.handled = true; void Window_ManipulationDelta(object sender, ManipulationDeltaEventArgs e) Rectangle recttomove = e.originalsource as Rectangle; Matrix rectsmatrix = ((MatrixTransform)rectToMove.RenderTransform).Matrix; rectsmatrix.rotateat(e.deltamanipulation.rotation, e.manipulationorigin.x, e.manipulationorigin.y); rectsmatrix.scaleat(e.deltamanipulation.scale.x, e.deltamanipulation.scale.x, e.manipulationorigin.x, e.manipulationorigin.y); rectsmatrix.translate(e.deltamanipulation.translation.x, e.deltamanipulation.translation.y); 200

208 recttomove.rendertransform = new MatrixTransform(rectsMatrix); Rect containingrect = new Rect(((FrameworkElement)e.ManipulationContainer).RenderSize); Rect shapebounds = recttomove.rendertransform.transformbounds(new Rect(rectToMove.RenderSize)); if (e.isinertial &&!containingrect.contains(shapebounds)) e.complete(); e.handled = true; void Window_InertiaStarting(object sender, ManipulationInertiaStartingEventArgs e) ); ); e.translationbehavior.desireddeceleration = 10.0 * 96.0 / ( * e.expansionbehavior.desireddeceleration = 0.1 * 96 / ( * e.rotationbehavior.desireddeceleration = 720 / ( * ); e.handled = true; When you compile and execute the above code, it will produce the following widnow. 201

209 Now you can rotate, zoom in, zoom out this image with your finger on touch screen. 202

210 36. WPF COMMAND LINE WPF Command line argument is a mechanism where a user can pass a set of parameters or values to a WPF application when it is executed. These arguments are very important to control an application from outside, for example, if you want to open a Word document from the command prompt, then you can use this command C:\> start winword word1.docx and it will open word1.docx document. Command line arguments are handled in Startup function. Following is a simple example which shows how to pass command line arguments to a WPF application. Let s create a new WPF application with the name WPFCommandLine. 1. Drag one textbox from the toolbox to the design window. 2. In this example, we will pass a txt file path to our application as command line parameter. 3. The program will read the txt file and then write all the text on the text box. 4. The following XAML code creates a textbox and initializes it with some properties. <Window x:class="wpfcommandline.mainwindow" <Grid> </Grid> </Window> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfcommandline" mc:ignorable="d" Title="MainWindow" Height="350" Width="525"> <TextBox x:name="textbox" HorizontalAlignment="Left" Height="180" Margin="100" TextWrapping="Wrap" VerticalAlignment="Top" Width="300"/> 5. Now subscribe the Startup event in App.xaml file as shown below. <Application x:class="wpfcommandline.app" xmlns=" xmlns:x=" 203

211 xmlns:local="clr-namespace:wpfcommandline" StartupUri="MainWindow.xaml" Startup="app_Startup"> <Application.Resources> </Application.Resources> </Application> 6. Given below is the implementation of the app_startup event in App.xaml.cs which will get the command line arguments. using System.Windows; namespace WPFCommandLine /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application public static string[] Args; void app_startup(object sender, StartupEventArgs e) // If no command line arguments were provided, don't process them if (e.args.length == 0) return; if (e.args.length > 0) Args = e.args; 7. Now, in the MainWindow class, the program will open the txt file and write all the text on textbox. 8. If there is some error found, then the program will display an error message on textbox. 204

212 using System; using System.IO; using System.Windows; namespace WPFCommandLine public partial class MainWindow : Window public MainWindow() InitializeComponent(); String[] args = App.Args; try // Open the text file using a stream reader. using (StreamReader sr = new StreamReader(args[0])) // Read the stream to a string, and write // the string to the text box String line = sr.readtoend(); textbox.appendtext(line.tostring()); textbox.appendtext("\n"); catch (Exception e) textbox.appendtext("the file could not be read:"); textbox.appendtext("\n"); textbox.appendtext(e.message); 9. When the above code is compiled and executed, it will produce a blank window with a textbox because this program needs a command line argument. So Visual Studio provides an easy way to execute your application with command line parameters. 205

213 10. Right click on your WPF project in the solution explorer and select properties, it will display the following window. 11. Select Debug option and write the file path in the Command line argument. 12. Create a txt file with Test.txt and write some text in that file and save it on any location. In this case, the txt file is saved on D:\ hard drive. 13. Save the changes in your project and compile and execute your application now. You will see the text in TextBox which the program reads from the Text.txt file. 206

214 Now let s try and change the file name on your machine from Test.txt to Test1.txt and execute your program again, then you will see that error message in the text box. We recommend that you execute the above code and follow all the steps to execute your application successfully. 207

215 37. WPF DATA BINDING WPF Data binding is a mechanism in WPF applications that provides a simple and easy way for Windows Runtime apps to display and interact with data. In this mechanism, the management of data is entirely separated from the way data. Data binding allows the flow of data between UI elements and data object on user interface. When a binding is established and the data or your business model changes, then it reflects the updates automatically to the UI elements and vice versa. It is also possible to bind, not to a standard data source, but to another element on the page. Data binding is of two types: one-way data binding and two-way data binding. One-Way Data Binding In one-way binding, data is bound from its source (that is the object that holds the data) to its target (that is the object that displays the data) 1. Let s take a simple example to understand one-way data binding in detail. First of all, create a new WPF project with the name WPFDataBinding. 2. The following XAML code creates two labels, two textboxes, and one button and initializes them with some properties. <Window x:class="wpfdatabinding.mainwindow" <Grid> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfdatabinding" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="200" /> </Grid.ColumnDefinitions> 208

216 <Label Name="nameLabel" Margin="2">_Name:</Label> <TextBox Name="nameText" Grid.Column="1" Margin="2" Text="Binding Name, Mode=OneWay"/> <Label Name="ageLabel" Margin="2" Grid.Row="1">_Age:</Label> <TextBox Name="ageText" Grid.Column="1" Grid.Row="1" Margin="2" Text="Binding Age, Mode=OneWay"/> <StackPanel Grid.Row="2" Grid.ColumnSpan="2"> <Button Content="_Show..." Click="Button_Click" /> </StackPanel> </Grid> </Window> 3. The text properties of both the textboxes bind to Name and Age which are class variables of Person class which is shown below. 4. In Person class, we have just two variables Name and Age, and its object is initialized in MainWindow class. 5. In XAML code, we are binding to a property Name and Age, but we have not selected what object that property belongs to. 6. The easier way is to assign an object to DataContext whose properties we are binding in the following C# code in MainWindowconstructor. using System.Windows; namespace WPFDataBinding public partial class MainWindow : Window Person person = new Person Name = "Salman", Age = 26 ; public MainWindow() InitializeComponent(); this.datacontext = person; private void Button_Click(object sender, RoutedEventArgs e) 209

217 string message = person.name + " is " + person.age; MessageBox.Show(message); public class Person private string namevalue; public string Name get return namevalue; set namevalue = value; private double agevalue; public double Age get return agevalue; set if (value!= agevalue) agevalue = value; 7. Let's run this application and you can see immediately in our MainWindow that we have successfully bound to the Name and Age of that Person object. 210

218 When you press the Show button, it will display the name and age on the message box. Let s change the Name and Age in the dialog box. If you now click the Show button, it will again display the same message. This because data binding mode is set to one-way in the XAML code. To show the updated data, you will need to understand two-way data binding. 211

219 Two-Way Data Binding In two-way binding, the user can modify the data through the user interface and have that data updated in the source. If the source changes while the user is looking at the view, you want the view to be updated. Let s take the same example but here, we will change the binding mode from One Way to Two Way in the XAML code. <Window x:class="wpfdatabinding.mainwindow" <Grid> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfdatabinding" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="200" /> </Grid.ColumnDefinitions> <Label Name="nameLabel" Margin="2">_Name:</Label> <TextBox Name="nameText" Grid.Column="1" Margin="2" Text="Binding Name, Mode=TwoWay"/> <Label Name="ageLabel" Margin="2" Grid.Row="1">_Age:</Label> <TextBox Name="ageText" Grid.Column="1" Grid.Row="1" Margin="2" Text="Binding Age, Mode=TwoWay"/> <StackPanel Grid.Row="2" Grid.ColumnSpan="2"> <Button Content="_Show..." Click="Button_Click" /> </StackPanel> </Grid> 212

220 </Window> Let's run this application again. It will produce the same output: Let s now change the Name and Age values: If you click the Show button now, it will display the updated message. 213

221 We recommend that you execute the above code with both the cases for a better understanding of the concept. 214

222 38. WPF RESOURCES WPF Resources are normally definitions connected with some object that you just anticipate to use more often than once. It is the ability to store data locally for controls or for the current window or globally for the entire applications. Defining an object as a resource allows us to access it from another place. What it means is that the object can be reused. Resources are defined in resource dictionaries and any object can be defined as a resource effectively making it a shareable asset. A unique key is specified to an XAML resource and with that key, it can be referenced by using a StaticResource markup extension. Resources can be of two types: StaticResource DynamicResource A StaticResource is a onetime lookup, whereas a DynamicResource works more like a data binding. It remembers that a property is associated with a particular resource key. If the object associated with that key changes, dynamic resource will update the target property. Example Here's a simple application for the SolidColorBrush resource. 1. Let s create a new WPF project with the name WPFResouces. 2. Drag two Rectangles and set their properties as shown in the following XAML code. <Window x:class="wpfresources.mainwindow" xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfresources" mc:ignorable="d" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <SolidColorBrush x:key="brushresource" Color="Blue" /> </Window.Resources> <StackPanel> <Rectangle Height="50" Margin="20" Fill="StaticResource brushresource" /> 215

223 <Rectangle Height="50" Margin="20" Fill="DynamicResource brushresource"/> <Button x:name="changeresourcebutton" Content="_Change Resource" Click="changeResourceButton_Click" /> </StackPanel> </Window> 3. In the above XAML code, you can see that one rectangle has StaticResource and the other one has DynamicResource and the color of brushresource is Bisque. 4. When you compile and execute the code, it will produce the following MainWindow. When you click the "Change Resource" button, you will see that the rectangle with DynamicResource will change its color to Red. 216

224 Resource Scope Resources are defined in resource dictionaries, but there are numerous places where a resource dictionary can be defined. In the above example, a resource dictionary is defined on Window/page level. In what dictionary a resource is defined immediately limits the scope of that resource. So the scope, i.e. where you can use the resource, depends on where you've defined it. Define the resource in the resource dictionary of a grid and it's accessible by that grid and by its child elements only. Define it on a window/page and it's accessible by all elements on that window/page. The app root can be found in App.xaml resources dictionary. It's the root of our application, so the resources defined here are scoped to the entire application. As far as the scope of the resource is concerned, the most often are application level, page level, and a specific element level like a Grid, StackPanel, etc. The above application has resources in its Window/page level. Resource Dictionaries Resource dictionaries in XAML apps imply that the resource dictionaries are kept in separate files. It is followed in almost all XAML apps. Defining resources in separate files can have the following advantages: Separation between defining resources in the resource dictionary and UI related code. Defining all the resources in a separate file such as App.xaml would make them available across the app. 217

225 So, how do we define our resources in a resource dictionary in a separate file? Well, it is very easy, just add a new resource dictionary through Visual Studio by following steps given below: In your solution, add a new folder and name it ResourceDictionaries. Right-click on this folder and select Resource Dictionary from Add submenu item and name it DictionaryWithBrush.xaml Example Let s now take the same example, but here, we will define the resource dictionary in app level. The XAML code for MainWindow.xaml is as follows: <Window x:class="wpfresources.mainwindow" xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfresources" mc:ignorable="d" Title="MainWindow" Height="350" Width="525"> <StackPanel> <Rectangle Height="50" Margin="20" Fill="StaticResource brushresource" /> <Rectangle Height="50" Margin="20" Fill="DynamicResource brushresource"/> <Button x:name="changeresourcebutton" Content="_Change Resource" Click="changeResourceButton_Click" /> </StackPanel> </Window> Here is the implementation in DictionaryWithBrush.xaml: <ResourceDictionary xmlns=" xmlns:x=" <SolidColorBrush x:key="brushresource" Color="Blue" /> </ResourceDictionary> Here is the implementation in app.xaml: <Application x:class="wpfresources.app" xmlns=" xmlns:x=" 218

226 StartupUri="MainWindow.xaml"> <Application.Resources> <ResourceDictionary Source=" XAMLResources\ResourceDictionaries\DictionaryWithBrush.xaml"/> </Application.Resources> </Application> When the above code is compiled and executed, it will produce the following output: When you click the Change Resource button, the rectangle will change its color to Red. We recommend that you execute the above code and try some more resources (for example, background color). 219

227 39. WPF TEMPLATES WPF A template describes the overall look and visual appearance of a control. For each control, there is a default template associated with it which gives the control its appearance. In WPF applications, you can easily create your own templates when you want to customize the visual behavior and visual appearance of a control. Connectivity between the logic and the template can be achieved by data binding. The main difference between styles and templates are listed below: Styles can only change the appearance of your control with default properties of that control. With templates, you can access more parts of a control than in styles. You can also specify both existing and new behavior of a control. There are two types of templates which are most commonly used: Control Template Data Template Control Template The Control Template defines the visual appearance of a control. All of the UI elements have some kind of appearance as well as behavior, e.g., Button has an appearance and behavior. Click event or mouse hover event are the behaviors which are fired in response to a click and hover and there is also a default appearance of button which can be changed by the Control template. Example Let s take a simple example. We will create two buttons (one is with template and the other one is the default button) and initialize them with some properties. <Window x:class="templatedemo.mainwindow" xmlns=" xmlns:x=" Title="MainWindow" Height="350" Width="604"> <Window.Resources> <ControlTemplate x:key="buttontemplate" TargetType="Button"> <Grid> <Ellipse x:name="buttonellipse" Height="100" Width="150" > <Ellipse.Fill> <LinearGradientBrush StartPoint="0,0.2" EndPoint="0.2,1.4"> 220

228 <GradientStop Offset="0" Color="Red"/> <GradientStop Offset="1" Color="Orange"/> </LinearGradientBrush> </Ellipse.Fill> </Ellipse> <ContentPresenter Content="TemplateBinding Content" HorizontalAlignment="Center" VerticalAlignment="Center" /> </Grid> <ControlTemplate.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="ButtonEllipse" Property="Fill" > <Setter.Value> <LinearGradientBrush StartPoint="0,0.2" EndPoint="0.2,1.4"> <GradientStop Offset="0" Color="YellowGreen"/> <GradientStop Offset="1" Color="Gold"/> </LinearGradientBrush> </Setter.Value> </Setter> </Trigger> <Trigger Property="IsPressed" Value="True"> <Setter Property="RenderTransform"> <Setter.Value> <ScaleTransform ScaleX="0.8" ScaleY="0.8" CenterX="0" CenterY="0" /> </Setter.Value> </Setter> <Setter Property="RenderTransformOrigin" Value="0.5,0.5" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Window.Resources> <StackPanel> <Button Content="Round Button!" 221

229 Template="StaticResource ButtonTemplate" Width="150" Margin="50" /> <Button Content="Default Button!" Height="40" Width="150" Margin="5" /> </StackPanel> </Window> When you compile and execute the above code, it will display the following MainWindow. When you hove the mouse over the button with custom template, it will change its color as shown below. Data Template A Data Template defines and specifies the appearance and structure of a collection of data. It provides the flexibility to format and define the presentation of the data on any UI element. It is mostly used on data related Item controls such as ComboBox, ListBox, etc. 222

230 Example 1. Let s take a simple example to understand the concept of data template. Create a new WPF project with the name WPFDataTemplates. 2. In the following XAML code, we will create a Data Template as resource to hold labels and textboxes. There is a button and a list box as well which to display the data. <Window x:class="wpfdatatemplates.mainwindow" xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfdatatemplates" xmlns:loc="clr-namespace:wpfdatatemplates" mc:ignorable="d" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <DataTemplate DataType="x:Type loc:person"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="Auto" /> <ColumnDefinition Width="200" /> </Grid.ColumnDefinitions> <Label Name="nameLabel" Margin="10"/> <TextBox Name="nameText" Grid.Column="1" Margin="10" Text="Binding Name"/> <Label Name="ageLabel" Margin="10" Grid.Row="1"/> <TextBox Name="ageText" Grid.Column="1" Grid.Row="1" Margin="10" Text="Binding Age"/> </Grid> </DataTemplate> </Window.Resources> 223

231 <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <ListBox ItemsSource="Binding" /> <StackPanel Grid.Row="1" > <Button Content="_Show..." Click="Button_Click" Width="80" HorizontalAlignment="Left" Margin="10"/> </Grid> </Window> </StackPanel> Here is implementation in C# in which a list of Person objects are assigned to DataContext, implementation of Person class and button click event. using System.Collections.Generic; using System.Windows; namespace WPFDataTemplates public partial class MainWindow : Window Person src = new Person Name = "Ali", Age = 27 ; List<Person> people = new List<Person>(); public MainWindow() InitializeComponent(); people.add(src); people.add(new Person Name = "Mike", Age = 62 ); people.add(new Person Name = "Brian", Age = 12 ); this.datacontext = people; private void Button_Click(object sender, RoutedEventArgs e) 224

232 string message = src.name + " is " + src.age; MessageBox.Show(message); public class Person private string namevalue; public string Name get return namevalue; set namevalue = value; private double agevalue; public double Age get return agevalue; set if (value!= agevalue) agevalue = value; When you compile and execute the above code, it will produce the following window. It contains one list and inside the list box, each list box item contains the Person class object data which are displayed on Labels and Text boxes. 225

233 226

234 40. WPF STYLES WPF The.NET framework provides several strategies to personalize and customize the appearance of an application. Styles provide us the flexibility to set some properties of an object and reuse these specific settings across multiple objects for a consistent look. In styles, you can set only the existing properties of an object such as Height, Width, Font size, etc. Only default behavior of a control can be specified. Multiple properties can be added into a single style. Styles are used to give a uniform look or appearance to a set of controls. Implicit styles are used to apply an appearance to all the controls of a given type and simplify the application. Imagine three buttons, all of them have to look the same, same width and height, same font size, same foreground color, etc. We can set all those properties on the button elements themselves and that's still quite okay for all of the buttons. Take a look at the following diagram. But in a real-life applications, you'll typically have a lot more of these that need to look exactly the same. And not only buttons of course, you'll typically want your text blocks, text boxes, and combo boxes etc. to look the same across your application. Surely, there must be a better way to achieve this and it is known as styling. You can think of a style as a convenient way to apply a set of property values to more than one element. Take a look at the following diagram. 227

235 Example Let s take a simple example to understand this concept. Start by creating a new WPF project. 1. Drag three buttons from the toolbox to the design window. 2. The following XAML code creates three buttons and initializes them with some properties. <Window x:class="wpfstyle.mainwindow" xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace: WPFStyle" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <StackPanel> <Button Content="Button1" Height="30" Width="80" Foreground="Blue" FontSize="12" Margin="10"/> <Button Content="Button2" 228

236 Height="30" Width="80" Foreground="Blue" FontSize="12" Margin="10"/> <Button Content="Button3" </StackPanel> </Window> Height="30" Width="80" Foreground="Blue" FontSize="12" Margin="10"/> When you look at the above code, you will see that for all the buttons height, width, foreground color, font size and margin properties are same. Now when the above code is compiled and executed the following window will be displayed. Now let s have a look at the same example, but this time, we will be using style. <Window x:class="xamlstyle.mainwindow" xmlns=" xmlns:x=" xmlns:d=" 229

237 xmlns:mc=" xmlns:local="clr-namespace:xamlstyle" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <Window.Resources> <Style x:key="mybuttonstyle" TargetType="Button"> </Style> <Setter Property="Height" Value="30"/> <Setter Property="Width" Value="80"/> <Setter Property="Foreground" Value="Blue"/> <Setter Property="FontSize" Value="12"/> <Setter Property="Margin" Value="10"/> </Window.Resources> <StackPanel> <Button Content="Button1" Style="StaticResource mybuttonstyle"/> <Button Content="Button2" Style="StaticResource mybuttonstyle"/> <Button Content="Button3" Style="StaticResource mybuttonstyle"/> </StackPanel> </Window> Styles are defined in the resource dictionary and each style has a unique key identifier and a target type. Inside <style> you can see that multiple setter tags are defined for each property which will be included in the style. In the above example, all of the common properties of each button are now defined in style and then the style are assigned to each button with a unique key by setting the style property through the StaticResource markup extension. When you compile and execute the above code, it will display the following window (the same output). 230

238 The advantage of doing it like this is immediately obvious, we can reuse that style anywhere in its scope; and if we need to change it, we simply change it once in the style definition instead of on each element. In what level a style is defined instantaneously limits the scope of that style. So the scope, i.e. where you can use the style, depends on where you've defined it. Styles can be defined on the following levels: Control level Layout level Window level Application level Control Level Defining a style on control level can only be applied to that particular control. Given below is an example of a control level where the button and TextBlock have their own style. <Window x:class="xamlcontrollevelstyle.mainwindow" xmlns=" xmlns:x=" Title="Control Level Styles" Height="350" Width="604"> <StackPanel Margin="10" VerticalAlignment="Top"> <TextBlock Text="TextBlock"> <TextBlock.Style> <Style> <Setter Property="TextBlock.FontSize" Value="24" /> 231

239 <Setter Property="TextBlock.Width" Value="400" /> <Setter Property="TextBlock.Height" Value="40" /> <Setter Property="TextBlock.Background" Value="Gray" /> <Setter Property="TextBlock.Margin" Value="50" /> </Style> </TextBlock.Style> </TextBlock> <Button Content="Button"> <Button.Style> <Style> <Setter Property="TextBlock.Width" Value="100" /> <Setter Property="TextBlock.Height" Value="40" /> <Setter Property="TextBlock.Margin" Value="50" /> </Style> </Button.Style> </Button> </StackPanel> </Window> When the above code is compiled and executed, it will produce the following window: Layout Level Defining a style on any layout level will make it accessible by that layout and its child elements only. Given below is an example of layout level where all the three buttons have common style. 232

240 <Window x:class="xamllayoutlevelstyle.mainwindow" xmlns=" xmlns:x=" Title="MainWindow" Height="350" Width="604"> <StackPanel Margin="10"> <StackPanel.Resources> <Style TargetType="Button"> <Setter Property="Foreground" Value="Blue" /> <Setter Property="FontStyle" Value="Italic" /> <Setter Property="Width" Value="100" /> <Setter Property="Height" Value="40" /> <Setter Property="Margin" Value="10" /> </Style> </StackPanel.Resources> <Button>Button 1</Button> <Button>Button 2</Button> <Button Foreground="Blue">Button 3</Button> </StackPanel> </Window> When you compile and execute the above code, it will produce the following window. 233

241 Window Level Defining a style on a window level can make it accessible by all the elements on that window. Given below is an example of window level where all the three text blocks have a common style. <Window x:class="styles.mainwindow" xmlns=" xmlns:x=" Title="MainWindow" Height="350" Width="604"> <Window.Resources> <Style TargetType="TextBlock"> </Style> <Setter Property="FontSize" Value="24" /> <Setter Property="Margin" Value="5" /> <Setter Property="FontWeight" Value="Bold" /> <Style TargetType="TextBox"> </Style> </Window.Resources> <Grid> <Setter Property="HorizontalAlignment" Value="Left" /> <Setter Property="FontSize" Value="24" /> <Setter Property="Margin" Value="5" /> <Setter Property="Width" Value="200" /> <Setter Property="Height" Value="40" /> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="2*" /> </Grid.ColumnDefinitions> <TextBlock Text="First Name: "/> <TextBox Name="FirstName" Grid.Column="1" /> <TextBlock Text="Last Name: " Grid.Row="1" /> 234

242 <TextBox Name="LastName" Grid.Column="1" Grid.Row="1" /> <TextBlock Text=" " Grid.Row="2" /> <TextBox Name=" " Grid.Column="1" Grid.Row="2"/> </Grid> </Window> When you compile and execute the above code, it will produce the following window. Application Level Defining a style on app level can make it accessible throughout the entire application. Let s take the same example, but here, we will put the styles in app.xaml file to make it accessible throughout application. Here is the XAML code in app.xaml. <Application x:class="styles.app" xmlns=" xmlns:x=" StartupUri="MainWindow.xaml"> <Application.Resources> <Style TargetType="TextBlock"> </Style> <Setter Property="FontSize" Value="24" /> <Setter Property="Margin" Value="5" /> <Setter Property="FontWeight" Value="Bold" /> <Style TargetType="TextBox"> 235

243 <Setter Property="HorizontalAlignment" Value="Left" /> <Setter Property="FontSize" Value="24" /> <Setter Property="Margin" Value="5" /> <Setter Property="Width" Value="200" /> <Setter Property="Height" Value="40" /> </Style> </Application.Resources> </Application> Here is the XAML code to create text blocks and text boxes. <Window x:class="styles.mainwindow" xmlns=" xmlns:x=" Title="MainWindow" Height="350" Width="604"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="Auto" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="*" /> <ColumnDefinition Width="2*" /> </Grid.ColumnDefinitions> <TextBlock Text="First Name: "/> <TextBox Name="FirstName" Grid.Column="1" /> <TextBlock Text="Last Name: " Grid.Row="1" /> <TextBox Name="LastName" Grid.Column="1" Grid.Row="1" /> <TextBlock Text=" " Grid.Row="2" /> <TextBox Name=" " Grid.Column="1" Grid.Row="2"/> </Grid> </Window> When you compile and execute the above code, it will produce the following window. 236

244 We recommend that you execute the above code and try to insert more features into it. 237

245 41. WPF TRIGGERS WPF A trigger basically enables you to change property values or take actions based on the value of a property. So, it allows you to dynamically change the appearance and/or behavior of your control without having to create a new one. Triggers are used to change the value of any given property, when certain conditions are satisfied. Triggers are usually defined in a style or in the root of a document which are applied to that specific control. There are three types of triggers: Property Triggers Data Triggers Event Triggers Property Triggers In property triggers, when a change occurs in one property, it will bring either an immediate or an animated change in another property. For example, you can use a property trigger to change the appearance of a button when the mouse hovers over the button. The following example code shows how to change the foreground color of a button when mouse hovers over the button. <Window x:class="wpfpropertytriggers.mainwindow" xmlns=" xmlns:x=" Title="MainWindow" Height="350" Width="604"> <Window.Resources> <Style x:key="triggerstyle" TargetType="Button"> </Style> <Setter Property="Foreground" Value="Blue" /> <Style.Triggers> <Trigger Property="IsMouseOver" Value="True"> <Setter Property="Foreground" Value="Green" /> </Trigger> </Style.Triggers> </Window.Resources> <Grid> <Button Width="100" Height="70" 238

246 Style="StaticResource TriggerStyle" Content="Trigger"/> </Grid> </Window> When you compile and execute the above code, it will produce the following window: When the mouse hovers over the button, its foreground color will change to green. Data Triggers A data trigger performs some actions when the bound data satisfies some conditions. Let s have a look at the following XAML code in which a checkbox and a text block are created 239

247 with some properties. When the checkbox is checked, it will change its foreground color to red. <Window x:class="wpfdatatrigger.mainwindow" xmlns=" xmlns:x=" Title="Data Trigger" Height="350" Width="604"> <StackPanel HorizontalAlignment="Center"> <CheckBox x:name="redcolorcheckbox" Content="Set red as foreground color" Margin="20"/> <TextBlock Name="txtblock" VerticalAlignment="Center" Text="Event Trigger" FontSize="24" Margin="20"> <TextBlock.Style> <Style> <Style.Triggers> <DataTrigger Binding="Binding ElementName=redColorCheckBox, Path=IsChecked" </Style> Value="true"> <Setter Property="TextBlock.Foreground" Value="Red"/> <Setter Property="TextBlock.Cursor" Value="Hand" /> </DataTrigger> </Style.Triggers> </TextBlock.Style> </TextBlock> </StackPanel> </Window> When the above code is compiled and executed, it will produce the following output: 240

248 When you tick the checkbox, the text block will change its foreground color to red. Event Triggers An event trigger performs some actions when a specific event is fired. It is usually used to accomplish some animation on control such DoubleAnumatio, ColorAnimation, etc. In the following example, we will create a simple button. When the click event is fired, it will expand the button width and height. <Window x:class="wpfeventtrigger.mainwindow" 241

249 <Grid> xmlns=" xmlns:x=" Title="MainWindow" Height="350" Width="604"> <Button Content="Click Me" Width="60" Height="30"> <Button.Triggers> <EventTrigger RoutedEvent="Button.Click"> <EventTrigger.Actions> <BeginStoryboard> <Storyboard> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="Width" Duration="0:0:4"> <LinearDoubleKeyFrame Value="60" KeyTime="0:0:0"/> <LinearDoubleKeyFrame Value="120" KeyTime="0:0:1"/> <LinearDoubleKeyFrame Value="200" KeyTime="0:0:2"/> <LinearDoubleKeyFrame Value="300" </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="Height" KeyTime="0:0:3"/> Duration="0:0:4"> <LinearDoubleKeyFrame Value="30" KeyTime="0:0:0"/> <LinearDoubleKeyFrame Value="40" KeyTime="0:0:1"/> <LinearDoubleKeyFrame Value="80" KeyTime="0:0:2"/> <LinearDoubleKeyFrame Value="150" KeyTime="0:0:3"/> </DoubleAnimationUsingKeyFrames> 242

250 </Storyboard> </BeginStoryboard> </EventTrigger.Actions> </EventTrigger> </Button.Triggers> </Button> </Grid> </Window> When you compile and execute the above code, it will produce the following window: Upon clicking the button, you will observe that it will start expanding in both dimensions. We recommend that you compile and execute the above examples and apply the triggers to other properties as well. 243

251 42. WPF DEBUGGING WPF It is a systematic mechanism of identifying and fixing the bugs or defects in a piece of code which are not behaving the same as you are expecting. Debugging a complex application where the subsystems are tightly coupled are not that easy, because fixing bugs in one subsystem can create bugs in another subsystem. Debugging in C# In WPF applications, programmers deal with two languages such as C# and XAML. If you are familiar with debugging in any procedural language such as C# or C/C++ and you also know the usage of break points, then you can debug the C# part of your application easily. Let s take a simple example to demonstrate how to debug a C# code. Create a new WPF project with the name WPFDebuggingDemo. Drag four labels, three textboxes, and one button from the toolbox. Take a look at the following XAML code. <Window x:class="wpfdebuggingdemo.window1" xmlns=" xmlns:x=" Title="Window1" Height="400" Width="604"> <Grid> <TextBox Height="23" Margin="0,44,169,0" Name="textBox1" VerticalAlignment="Top" HorizontalAlignment="Right" Width="120" /> <TextBox Height="23" Margin="0,99,169,0" Name="textBox2" VerticalAlignment="Top" HorizontalAlignment="Right" Width="120" /> <TextBox HorizontalAlignment="Right" Margin="0,153,169,0" Name="textBox3" Width="120" Height="23" VerticalAlignment="Top" /> <Label Height="28" Margin="117,42,0,0" Name="label1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="120">Item 1</Label> <Label Height="28" HorizontalAlignment="Left" Margin="117,99,0,0" Name="label2" VerticalAlignment="Top" Width="120">Item 2</Label> <Label HorizontalAlignment="Left" Margin="117,153,0,181" Name="label3" Width="120">Item 3</Label> 244

252 <Button Height="23" HorizontalAlignment="Right" Margin="0,0,214,127" Name="button1" VerticalAlignment="Bottom" Width="75" Click="button1_Click">Total</Button> <Label Height="28" HorizontalAlignment="Right" Margin="0,0,169,66" Name="label4" VerticalAlignment="Bottom" Width="120"/> </Grid> </Window> Given below is the C# code in which a button click event is implemented. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace WPFDebuggingDemo /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window public Window1() InitializeComponent(); 245

253 private void button1_click(object sender, RoutedEventArgs e) if (textbox1.text.length > 0 && textbox2.text.length > 0 && textbox2.text.length > 0) double total = Convert.ToDouble(textBox1.Text) + Convert.ToDouble(textBox2.Text) + Convert.ToDouble(textBox3.Text); else label4.content = total.tostring(); MessageBox.Show("Enter the value in all field."); When you compile and execute the above code, it will produce the following window. Now enter values in the textboxes and press the Total button. You will get the total value after summation of all the values entered in the textboxes. If you try to enter values other than real values, then the above application will crash. To find and resolve the issue (why it is crashing), you can insert break points in the button click event. Let s write "abc" in item 1 as shown below. 246

254 Upon clicking the Total button, you will see that the program stops at the break point Now move the cursor towards the textbox1.text and you will see that the program is trying to add abc value with the other values which is why the program is crashing. 247

255 Debugging in XAML If you are expecting the same kind of debugging in XAML, then you will be surprised to know that it is not possible yet to debug the XAML code like debugging any other procedural language code. When you hear the term debugging in XAML code, it means try and find an error. In data binding, your data doesn't show up on screen and you don't know why Or an issue is related to complex layouts. Or an alignment issue or issues in margin color, overlays, etc. with some extensive templates like ListBox and combo box. Debugging an XAML program is something you typically do to check if your bindings work; and if it is not working, then to check what's wrong. Unfortunately setting breakpoints in XAML bindings isn't possible except in Silverlight, but we can use the Output window to check for data binding errors. Let's take a look at the following XAML code to find the error in data binding. <Window x:class="databindingoneway.mainwindow" <Grid> xmlns=" xmlns:x=" Title="MainWindow" Height="350" Width="604"> <StackPanel Name="Display"> <StackPanel Orientation="Horizontal" Margin="50, 50, 0, 0"> </StackPanel> <TextBlock Text="Name: " Margin="10" Width="100"/> <TextBlock Margin="10" Width="100" Text="Binding FirstName"/> <StackPanel Orientation="Horizontal" Margin="50,0,50,0"> </StackPanel> </StackPanel> </Grid> </Window> <TextBlock Text="Title: " Margin="10" Width="100"/> <TextBlock Margin="10" Width="100" Text="Binding Title" /> Text properties of two text blocks are set to Name and Title statically, while other two text blocks Text properties are bind to FirstName and Title but class variables are Name and Title in Employee class which is shown below. 248

256 We have intentionally written an incorrect variable name so as to understand where can we find this type of a mistake when the desired output is not shown. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataBindingOneWay public class Employee public string Name get; set; public string Title get; set; public static Employee GetEmployee() var emp = new Employee() Name = "Ali Ahmed", Title = "Developer" ; return emp; Here is the implementation of MainWindow class in C# code. using System; using System.Windows; using System.Windows.Controls; namespace DataBindingOneWay /// <summary> /// Interaction logic for MainWindow.xaml 249

257 /// </summary> public partial class MainWindow : Window public MainWindow() InitializeComponent(); DataContext = Employee.GetEmployee(); Let's run this application and you can see immediately in our MainWindow that we have successfully bound to the Title of that Employee object but the name is not bound. To check what happened with the name, let s look into the output window where a lot of log is generated. The easy to find an error is just to search for the error and you will find the following error which says BindingExpression path error: 'FirstName' property not found on 'object' ''Employe System.Windows.Data Error: 40 : BindingExpression path error: 'FirstName' property not found on 'object' ''Employee' (HashCode= )'. BindingExpression:Path=FirstName; DataItem='Employee' (HashCode= ); target element is 'TextBlock' (Name=''); target property is 'Text' (type 'String') 250

258 Which clearly indicate that FirstName is not a member of Employee class, so it helps to fix this type of issues in your application. When you change the FirstName to Name again, then you will see the desired output. UI Debugging Tools for XAML UI debugging tools were introduced for XAML with Visual Studio 2015 to inspect the XAML code at runtime. With the help of these tools, XAML code is presented in the form of a visual tree of your running WPF application and also the different UI element properties in the tree. To enable these tools, follow the steps given below. 1. Go to the Tools menu and select Options from the Tools menu. 2. It will open the following dialog box. 3. Go to the General Options under Debugging item on the left side. 4. Tick the highlighted option, i.e., Enable UI Debugging Tools for XAML and click the OK button. Now run any XAML application or use the following XAML code. <Window x:class="xamltestbinding.mainwindow" xmlns=" xmlns:x=" Title="MainWindow" Height="350" Width="604"> <StackPanel> <ComboBox Name="comboBox" Margin="50" Width="100"> <ComboBoxItem Content="Green"/> <ComboBoxItem Content="Yellow" IsSelected="True"/> 251

259 <ComboBoxItem Content="Orange" /> </ComboBox> <TextBox Name="textBox" Margin="50" Width="100" Height="23" VerticalAlignment="Top" </TextBox> </StackPanel> </Window> Text ="Binding ElementName=comboBox, Path=SelectedItem.Content, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged" Background="Binding ElementName=comboBox, Path=SelectedItem.Content"> When you execute the application, it will show the Live Visual Tree where all the elements are shown in a tree. 252

260 This Live Visual Tree shows the complete layout structure to understand where the UI elements are located. But this option is only available in Visual Studio If you are using an older option of Visual Studio, then you can t use this tool, however there is another tool which can be integrated with Visual Studio such as XAML Spy for Visual Studio. You can download it from 253

261 43. WPF CUSTOM CONTROLS WPF WPF applications allows to create custom controls which makes it very easy to create feature-rich and customizable controls. Custom controls are used when all the built-in controls provided by Microsoft are not fulfilling your criteria or you don t want to pay for third-party controls. In this chapter, you will learn how to create custom controls. Before we start taking a look at Custom Controls, let's take a quick look at a User Control first. User Control User Controls provide a way to collect and combine different built-in controls together and package them into re-usable XAML. User controls are used in following scenarios: If the control consists of existing controls, i.e., you can create a single control of multiple, already existing controls. If the control doesn't need support for theming. User Controls do not support complex customization, control templates, and difficult to style. If a developer prefers to write controls using the code-behind model where a view and then a direct code behind for event handlers. You won't be sharing your control across applications. Example Let s go to an example of User control and follow the steps given below. 1. Create a new WPF project and then right-click on your solution and select Add > New Item

262 2. The following window will open. Now select User Control (WPF) and name it MyUserControl. 255

263 3. Click the Add button and you will see that two new files (MyUserControl.xaml and MyUserControl.cs) will be added in your solution. Here is the XAML code in which a button and a text box is created with some properties in MyUserControl.xaml file. <UserControl x:class="wpfusercontrol.myusercontrol" <Grid> </Grid> </UserControl> xmlns=" xmlns:x=" xmlns:mc=" xmlns:d=" mc:ignorable="d" d:designheight="300" d:designwidth="300"> <TextBox Height="23" HorizontalAlignment="Left" Margin="80,49,0,0" Name="txtBox" VerticalAlignment="Top" Width="200" /> <Button Content="Click Me" Height="23" HorizontalAlignment="Left" Margin="96,88,0,0" Name="button" VerticalAlignment="Top" Width="75" Click="button_Click" /> Given below is the C# code for button click event in MyUserControl.cs file which updates the text box. using System; using System.Windows; using System.Windows.Controls; namespace WPFUserControl /// <summary> 256

264 /// Interaction logic for MyUserControl.xaml /// </summary> public partial class MyUserControl : UserControl public MyUserControl() InitializeComponent(); private void button_click(object sender, RoutedEventArgs e) txtbox.text = "You have just clicked the button"; Here is the implementation in MainWindow.xaml to add the user control. <Window x:class="xamlusercontrol.mainwindow" xmlns=" xmlns:x=" xmlns:control="clr-namespace:wpfusercontrol" Title="MainWindow" Height="350" Width="525"> <Grid> <control:myusercontrol/> </Grid> </Window> 257

265 When you compile and execute the above code, it will produce the following window. Upon clicking the "Click Me" button, you will notice that the text inside the textbox is updated. Custom Controls A custom control is a class which offers its own style and template which are normally defined in generic.xaml. Custom controls are used in the following scenarios: If the control doesn't exist and you have to create it from scratch. If you want to extend or add functionality to a preexisting control by adding an extra property or an extra functionality to fit your specific scenario. If your controls need to support theming and styling. If you want to share your control across applications. 258

266 Example Let s take an example to understand how custom controls work. Create a new WPF project and then right-click on your solution and select Add > New Item... It will open the following window. Now select Custom Control (WPF) and name it MyCustomControl. 259

267 Click the Add button and you will see that two new files (Themes/Generic.xaml and MyCustomControl.cs) will be added in your solution. Here is the XAML code in which style is set for the custom control in Generic.xaml file. <ResourceDictionary xmlns=" xmlns:x=" xmlns:local="clr-namespace:wpfcustomcontrols"> <Style TargetType="x:Type local:mycustomcontrol" BasedOn="StaticResource x:type Button"> <Setter Property="Background" Value="LightSalmon" /> <Setter Property="Foreground" Value="Blue"/> </Style> </ResourceDictionary> Here is the C# code for MyCustomControl class which is inherited from the button class and in constructor it overrides the metadata. using System; using System.Windows; using System.Windows.Controls; namespace WPFCustomControls public class MyCustomControl : Button static MyCustomControl() DefaultStyleKeyProperty.OverrideMetadata(typeof(MyCustomControl), new FrameworkPropertyMetadata(typeof(MyCustomControl))); Here is the custom control click event implementation in C# which updates the text of the text block. using System; using System.Windows; using System.Windows.Controls; 260

268 namespace WPFCustomControls /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window public MainWindow() InitializeComponent(); private void customcontrol_click(object sender, RoutedEventArgs e) txtblock.text = "You have just click your custom control"; Here is implementation in MainWindow.xaml to add the custom control and a TextBlock. <Window x:class="wpfcustomcontrols.mainwindow" xmlns=" xmlns:x=" xmlns:control="clr-namespace:wpfcustomcontrols" Title="MainWindow" Height="350" Width="604"> <StackPanel> <control:mycustomcontrol x:name="customcontrol" Content="Click Me" Width="70" Margin="10" Click="customControl_Click"/> <TextBlock Name="txtBlock" Width="250" Height="30"/> </StackPanel> 261

269 </Window> When you compile and execute the above code, it will produce the following window with a custom control which is a customized button. Upon clicking the customized button, you will see that the text inside text block is updated. 262

270 44. WPF EXCEPTION HANDLING WPF An exception is any error condition or an unexpected behavior that is encountered during the execution of a program. Exceptions can be raised due to many reasons, some of them are as follows: Fault in your code or in code that you call (such as a shared library), Unavailable operating system resources, Unexpected conditions that a common language runtime encounters (such as code that cannot be verified) Syntax Exceptions have the ability to transfer the flow of a program from one part to another. In.NET framework, exception handling has the following four keywords: try: In this block, the program identifies a certain condition which raises some exception. catch: The catch keyword indicates the catching of an exception. A try block is followed by one or more catch blocks to catch an exception with an exception handler at the place in a program where you want to handle the problem. finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not. throw: A program throws an exception when a problem shows up. This is done using a throw keyword. The syntax to use these four keywords goes as follows: try ///This will still trigger the exception catch (ExceptionClassName e) // error handling code catch (ExceptionClassName e) // error handling code 263

271 catch (ExceptionClassName e) finally // error handling code // statements to be executed Multiple catch statements are used in those cases where a try block can raise more than one exception depending on the situation of a program flow. Hierarchy Almost all the exception classes in the.net framework are directly or indirectly derived from the Exception class. The most important exception classes derived from the Exception class are: ApplicationException class It supports exceptions which are generated by programs. When developer want to define exception then class should be derived from this class. SystemException class It is the base class for all predefined runtime system exceptions. The following hierarchy shows the standard exceptions provided by the runtime. Object Exception System Exception IndexOutOfRa ngeexception NullReference Exception AccessViolatio nexception InvalidOperati onexception ArgumentExce ption ExternalExcept ion ArgumentNull Exception ArgumentOut OfRangeExcep tion SEHException 264

272 The following table lists the standard exceptions provided by the runtime and the conditions under which you should create a derived class. Exception type Base type Description Exception Object Base class for all exceptions. SystemException Exception Base class for all runtimegenerated errors. IndexOutOfRangeException SystemException Thrown by the runtime only when an array is indexed improperly. NullReferenceException SystemException Thrown by the runtime only when a null object is referenced. AccessViolationException SystemException Thrown by the runtime only when invalid memory is accessed. InvalidOperationException SystemException Thrown by methods when in an invalid state. ArgumentException SystemException Base class for all argument exceptions. ArgumentNullException ArgumentException Thrown by methods that do not allow an argument to be null. ArgumentOutOfRangeException ArgumentException Thrown by methods that verify that arguments are in a given range. ExternalException SystemException Base class for exceptions that occur or are targeted at environments outside the runtime. SEHException ExternalException Exception encapsulating Win32 structured exception handling information. Example Let s take a simple example to understand the concept better. Start by creating a new WPF project with the name WPFExceptionHandling. Drag one textbox from the toolbox to the design window. The following XAML code creates a textbox and initializes it with some properties. <Window x:class="wpfexceptionhandling.mainwindow" xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfexceptionhandling" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> 265

273 <Grid> <TextBox x:name="textbox" HorizontalAlignment="Left" Height="241" Margin="70,39,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="453"/> </Grid> </Window> Here is the file reading with exception handling in C#. using System; using System.IO; using System.Windows; namespace WPFExceptionHandling public partial class MainWindow : Window public MainWindow() InitializeComponent(); ReadFile(0); void ReadFile(int index) string path StreamReader file = new StreamReader(path); char[] buffer = new char[80]; try file.readblock(buffer, index, buffer.length); string str = new string(buffer); str.trim(); textbox.text = str; catch (Exception e) 266

274 e.message); MessageBox.Show("Error reading from "+ path + "\nmessage = "+ finally if (file!= null) file.close(); When you compile and execute the above code, it will produce the following window in which a text is displayed inside the textbox. When there is an exception raised or you throw it manually (as in the following code), then it will show a message box with error. using System; using System.IO; using System.Windows; namespace WPFExceptionHandling 267

275 public partial class MainWindow : Window public MainWindow() InitializeComponent(); ReadFile(0); void ReadFile(int index) string path StreamReader file = new StreamReader(path); char[] buffer = new char[80]; try file.readblock(buffer, index, buffer.length); string str = new string(buffer); throw new Exception(); str.trim(); textbox.text = str; catch (Exception e) e.message); MessageBox.Show("Error reading from "+ path + "\nmessage = "+ finally if (file!= null) file.close(); 268

276 When an exception is raised while executing the above code, it will display the following message. We recommend that you execute the above code and experiment with its features. 269

277 45. WPF LOCALIZATION WPF Localization is the translation of application resources into localized versions for the specific cultures that the application supports. When you develop your application and your application is available in only one language, then you are limiting the number of your customers and the size of your business. If you want to increase your customer base which will also increase your business, then your product must be available and reachable to a global audience. Cost-effective localization of your product is one of the best and most economical ways to reach out to more customers. In WPF, localizable applications are very easy to create with resx file which is the simplest solution for localization. Let s take a simple example to understand how it works: Create a new WPF project with the name WPFLocalization. In your solution explorer, you will see the Resources.resx file under Properties folder. 270

278 Change the access modifier from internal to public so that it can be accessible in XAML file. Now add the following string s name and values which we will be using in our application. 271

279 Make two copies of Resources.resx file with the names Resources.en.resx and Resources.ru-RU.resx. These are naming conventions specific to language and country/region name, and it can be found on National Language Support (NLS) API Reference ( page. Change the values in Resources.ru-RU.resx to Russian words, as shown below. 272

280 Let s go to the design window and drag three textboxes, three labels, and three buttons. In the XAML file, first add the namespace declaration to use localize resources xmlns:p="clr-namespace:wpflocalization.properties" Set the properties of all the controls as shown below. In this example, we will not use hardcoded strings for the content of labels, buttons, and Title of the window in XAML file. We will be using the strings which are defined in *.resx files. For example, for the Title of window, we use the Title string which is defined in *.resx file like this Title="x:Static p:resources.title" Here is the XAML file in which controls are created and initialized with different properties. <Window x:class="wpflocalization.mainwindow" xmlns=" xmlns:x=" xmlns:local="clr-namespace:wpflocalization" xmlns:p="clr-namespace:wpflocalization.properties" 273

281 Title="x:Static p:resources.title" Height="350" Width="604"> <Grid> <TextBox x:name="textbox" HorizontalAlignment="Left" Height="23" Margin="128,45,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="304"/> <Label x:name="label" Content="x:Static p:resources.name" HorizontalAlignment="Left" Margin="52,45,0,0" VerticalAlignment="Top" Width="86"/> <TextBox x:name="textbox1" HorizontalAlignment="Left" Height="23" Margin="128,102,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="304"/> <Label x:name="label1" Content="x:Static p:resources.address" HorizontalAlignment="Left" Margin="52,102,0,0" VerticalAlignment="Top" Width="86"/> <TextBox x:name="textbox2" HorizontalAlignment="Left" Height="23" Margin="128,157,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="80"/> <Label x:name="label2" Content="x:Static p:resources.age" HorizontalAlignment="Left" Margin="52,157,0,0" VerticalAlignment="Top" Width="86"/> <Button x:name="button" Content="x:Static p:resources.ok_button" HorizontalAlignment="Left" Margin="163,241,0,0" VerticalAlignment="Top" Width="75"/> <Button x:name="button1" Content="x:Static p:resources.cancel_button" HorizontalAlignment="Left" Margin="282,241,0,0" VerticalAlignment="Top" Width="75"/> <Button x:name="button2" Content="x:Static p:resources.help_button" HorizontalAlignment="Left" Margin="392,241,0,0" VerticalAlignment="Top" Width="75"/> </Grid> </Window> When the above code is compiled and executed you will see the following window which contains different controls. 274

282 By default, the program uses the default Resources.resx. If you want to show the text in Russian language which are defined in Resources.ru-RU.resx file, then you will need to set the culture explicitly when the program starts in App.xaml file as shown below. using System.Windows; namespace WPFLocalization /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application App() System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("ru-RU"); //System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo("en"); 275

283 When you run your application, you will see all the text in Russian language. We recommend that you execute the above code and create resx files for other cultures as well. 276

284 46. WPF INTERACTION WPF In WPF, an interaction shows how a view interacts with controls located in that view. The most commonly known interactions are of two types: Behaviors Drag and Drop Behaviors Behaviors were introduced with Expression Blend 3 which can encapsulate some of the functionality into a reusable component. To add additional behaviors, you can attach these components to the controls. Behaviors provide more flexibility to design complex user interactions easily. Let s take a look at a simple example in which a ControlStoryBoardAction behavior is attached to controls. Create a new WPF project with the name WPFBehavior. The following XAML code creates an ellipse and two buttons to control the movement of the ellipse. <Window xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfbehaviors" xmlns:i=" xmlns:ei=" x:class="wpfbehaviors.mainwindow" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <Window.Resources> <Storyboard x:key="storyboard1" RepeatBehavior="Forever" AutoReverse="True"> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children )[3].(TranslateTransform.X)" Storyboard.TargetName="ellipse"> <EasingDoubleKeyFrame KeyTime="0:0:1" Value=" "/> <EasingDoubleKeyFrame KeyTime="0:0:2" Value="2.909"/> </DoubleAnimationUsingKeyFrames> 277

285 <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children )[3].(TranslateTransform.Y)" Storyboard.TargetName="ellipse"> <EasingDoubleKeyFrame KeyTime="0:0:1" Value="-0.485"/> <EasingDoubleKeyFrame KeyTime="0:0:2" Value="0"/> </DoubleAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(ContentControl.Content)" Storyboard.TargetName="button"> <DiscreteObjectKeyFrame KeyTime="0" Value="Play"/> </ObjectAnimationUsingKeyFrames> <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="(ContentControl.Content)" Storyboard.TargetName="button1"> <DiscreteObjectKeyFrame KeyTime="0" Value="Stop"/> <DiscreteObjectKeyFrame KeyTime="0:0:2" Value="Stop"/> </ObjectAnimationUsingKeyFrames> </Storyboard> </Window.Resources> <Window.Triggers> <EventTrigger RoutedEvent="FrameworkElement.Loaded"> <BeginStoryboard Storyboard="StaticResource Storyboard1"/> </EventTrigger> </Window.Triggers> <Grid> <Ellipse x:name="ellipse" Fill="#FFAAAAC5" HorizontalAlignment="Left" Height="50.901" Margin="49.324,70.922,0,0" Stroke="Black" VerticalAlignment="Top" Width="73.684" RenderTransformOrigin="0.5,0.5"> <Ellipse.RenderTransform> <TransformGroup> <ScaleTransform/> <SkewTransform/> <RotateTransform/> <TranslateTransform/> </TransformGroup> </Ellipse.RenderTransform> </Ellipse> 278

286 <Button x:name="button" Content="Play" HorizontalAlignment="Left" Height="24.238" Margin="63.867,0,0,92.953" VerticalAlignment="Bottom" Width="74.654"> Storyboard1"/> <i:interaction.triggers> <i:eventtrigger EventName="Click"> <ei:controlstoryboardaction Storyboard="StaticResource </i:eventtrigger> </i:interaction.triggers> </Button> <Button x:name="button1" Content="Stop" HorizontalAlignment="Left" Height="24.239" Margin="160.82,0,0,93.922" VerticalAlignment="Bottom" Width="75.138"> <i:interaction.triggers> <i:eventtrigger EventName="Click"> <ei:controlstoryboardaction ControlStoryboardOption="Stop" Storyboard="StaticResource Storyboard1"/> </i:eventtrigger> </i:interaction.triggers> </Button> </Grid> </Window> When you compile and execute the above code, it will produce the following window which contains an ellipse and two buttons. 279

287 When you press the play button, it will start moving from left to right and then will return to its original position. The stop button will stop the movement the ellipse. Drag and Drop Drag and Drop on user interface can significantly advance the efficiency and productivity of the application. There are very few applications in which drag and drop features are used because people think it is difficult to implement. To an extent, it is difficult to handle a drag and drop feature, but in WPF, you can handle it quite easily. 280

288 Let s take a simple example to understand how it works. We will create an application wherein you can drag and drop color from one rectangle to another. 1. Create a new WPF project with the name WPFDragAndDrop. 2. Drag five rectangles to the design window and set the properties as shown in the following XAML file. <Window x:class="wpfdraganddrop.mainwindow" <Grid> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfdraganddrop" mc:ignorable="d" Title="MainWindow" Height=" " Width="604"> <Rectangle Name="Target" Fill="AliceBlue" HorizontalAlignment="Left" Height="345" Margin="10,10,0,0" Stroke="Black" VerticalAlignment="Top" Width="387" AllowDrop="True" Drop="Target_Drop"/> <Rectangle Fill="Beige" HorizontalAlignment="Left" Height="65" Margin="402,10,0,0" Stroke="Black" VerticalAlignment="Top" Width="184" MouseLeftButtonDown="Rect_MLButtonDown"/> <Rectangle Fill="LightBlue" HorizontalAlignment="Left" Height="65" Margin="402,80,0,0" Stroke="Black" VerticalAlignment="Top" Width="184" MouseLeftButtonDown="Rect_MLButtonDown"/> <Rectangle Fill="LightCoral" HorizontalAlignment="Left" Height="65" Margin="402,150,0,0" Stroke="Black" VerticalAlignment="Top" Width="184" MouseLeftButtonDown="Rect_MLButtonDown"/> <Rectangle Fill="LightGray" HorizontalAlignment="Left" Height="65" Margin="402,220,0,0" Stroke="Black" VerticalAlignment="Top" Width="184" MouseLeftButtonDown="Rect_MLButtonDown"/> <Rectangle Fill="OliveDrab" HorizontalAlignment="Left" Height="65" Margin="402,290,0,-7" Stroke="Black" VerticalAlignment="Top" Width="184" MouseLeftButtonDown="Rect_MLButtonDown"/> </Grid> </Window> 281

289 3. The first rectangle is the target rectangle, so the user can drag the color from the other rectangle to the target rectangle. 4. Given below are the events implementation in C# for drag and drop. using System.Windows; using System.Windows.Input; using System.Windows.Media; using System.Windows.Shapes; namespace WPFDragAndDrop /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window public MainWindow() InitializeComponent(); private void Rect_MLButtonDown(object sender, MouseButtonEventArgs e) Rectangle rc = sender as Rectangle; DataObject data = new DataObject(rc.Fill); DragDrop.DoDragDrop(rc, data,dragdropeffects.move); private void Target_Drop(object sender, DragEventArgs e) SolidColorBrush scb = (SolidColorBrush)e.Data.GetData(typeof(SolidColorBrush)); Target.Fill = scb; When you run your application, it will produce the following window. 282

290 If you drag a color from the rectangle on the right side and drop it on the large rectangle to the left, you will see its effect immediately. Let s drag the 4 th one from the right side. You can see that the color of the target rectangle has changed. We recommend that you execute the above code and experiment with its features. 283

291 47. WPF 2D GRAPHICS WPF WPF provides a wide range of 2D graphics which can be enhanced as per your application requirements. WPF supports both Drawing and Shape objects that are used for drawing graphical content. Shapes and Drawing Shape class is derived from the FrameworkElement class, Shape objects can be used inside panels and most controls. WPF provides some basic shape objects which are derived from the Shape class such as Ellipse, Line, Path, Polygon, Polyline, and Rectangle. Drawing objects, on the other hand, do not derive from the FrameworkElement class and provide a lighter-weight implementation. Drawing objects are simpler as compared to Shape objects. They have better performance characteristics as well. Example Let s take a simple example to understand how to use different shapes object. Create a new WPF project with the name WPF2DGraphics. The following code creates different types of shapes. <Window x:class="wpf2dgraphics.mainwindow" xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpf2dgraphics" xmlns:presentationoptions=" ation/options" mc:ignorable="presentationoptions" Title="MainWindow" Height="400" Width="604"> <StackPanel> <Ellipse Width="100" Height="60" Name="sample" Margin="10"> <Ellipse.Fill> <RadialGradientBrush> 284

292 <GradientStop Offset="0" Color="AliceBlue"/> <GradientStop Offset="1" Color="Gray"/> <GradientStop Offset="2" Color="Red"/> </RadialGradientBrush> </Ellipse.Fill> </Ellipse> <Path Stroke="Red" StrokeThickness="5" Data="M 10,70 L 200,70" Height="42.085" Stretch="Fill" Margin=" ,0, ,0" /> <Path Stroke="BlueViolet" StrokeThickness="5" Data="M 20,100 A 100, ,10" Height="81.316" Stretch="Fill" Margin=" ,0, ,0" /> <Path Fill="LightCoral" Margin=" ,0, ,0" Stretch="Fill" Height=" "> </Path> </StackPanel> </Window> <Path.Data> <PathGeometry> <PathFigure StartPoint="50,0" IsClosed="True"> <LineSegment Point="100,50"/> <LineSegment Point="50,100"/> <LineSegment Point="0,50"/> </PathFigure> </PathGeometry> </Path.Data> When you compile and execute the above code, it will produce an ellipse, a straight line, an arc, and a polygon. 285

293 Example Let s have a look at another example that shows how to paint an area with a drawing. 1. Create a new WPF project with the name WPF2DGraphics1. 2. The following XAML code shows how to paint different with image drawing. <Window x:class="wpf2dgraphics1.mainwindow" xmlns=" xmlns:x=" xmlns:d=" xmlns:presentationoptions=" ation/options" <Grid> xmlns:mc=" mc:ignorable="presentationoptions" xmlns:local="clr-namespace:wpf2dgraphics1" Title="MainWindow" Height="350" Width="604"> <Border BorderBrush="Gray" BorderThickness="1" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="20"> <Image Stretch="None"> 286

294 <Image.Source> <DrawingImage PresentationOptions:Freeze="True"> <DrawingImage.Drawing> <DrawingGroup> <ImageDrawing Rect="300,100,300,180" ImageSource="Images\DSC_0104.JPG"/> <ImageDrawing Rect="0,100,250,100" ImageSource="Images\DSC_0104.JPG"/> <ImageDrawing Rect="150,0,25,25" ImageSource="Images\DSC_0104.JPG"/> <ImageDrawing Rect="0,0,75,75" ImageSource="Images\DSC_0104.JPG"/> </Grid> </Window> </Image> </Border> </DrawingGroup> </DrawingImage.Drawing> </DrawingImage> </Image.Source> When you run your application, it will produce the following output: We recommend that you execute the above code and try more 2D shapes and drawings. 287

295 48. WPF 3D GRAPHICS WPF Windows Presentation Foundation (WPF) provides a functionality to draw, transform, and animate 3D graphics as per your application requirement. It doesn t support full fledge 3D game development, but to some level, you can create 3D graphics. By combining 2D and 3D graphics, you can also create rich controls, provide complex illustrations of data, or enhance the user experience of an application's interface. The Viewport3D element hosts a 3D model into our WPF application. Example Let s take a simple example to understand how to use 3D graphics. Create a new WPF project with the name WPF3DGraphics. The following XAML code shows how to create a 2D object using in 3D geometry. <Window x:class="wpf3dgraphics.mainwindow" xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpf3dgraphics" mc:ignorable="d" Title="MainWindow" Height="500" Width="604"> <Grid> <Viewport3D> <Viewport3D.Camera> <PerspectiveCamera Position="2,0,10" LookDirection="0.2,0.4,-1" FieldOfView="65" UpDirection="0,1,0" /> </Viewport3D.Camera> <ModelVisual3D> <ModelVisual3D.Content> <Model3DGroup> <AmbientLight Color="Bisque" /> <GeometryModel3D> <GeometryModel3D.Geometry> <MeshGeometry3D Positions="0,0,0 0,8,0 10,0,0 8,8,0" 288

296 Normals="0,0,1 0,0,1 0,0,1 0,0,1" TriangleIndices="0,2,1 1,2,3"/> </GeometryModel3D.Geometry> <GeometryModel3D.Material> <DiffuseMaterial Brush="Bisque" /> </GeometryModel3D.Material> </GeometryModel3D> </Model3DGroup> </ModelVisual3D.Content> </ModelVisual3D> </Viewport3D> </Grid> </Window> When you compile and execute the above code, it will produce a 2D object in 3D. Example Let s have a look at another example which shows a 3D object. 1. Create a new WPF project with the name WPF3DGraphics1. 2. The following XAML code creates a 3D object and a slider. With the help of the slider, you can rotate this 3D object. 289

297 <Window x:class="wpf3dgraphics1.mainwindow" <Grid> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpf3dgraphics1" mc:ignorable="d" Title="MainWindow" Height="350" Width="525"> <Viewport3D Name="viewport3D1"> <Viewport3D.Camera> <PerspectiveCamera x:name="cammain" Position="6 5 4" LookDirection=" "> " </PerspectiveCamera> </Viewport3D.Camera> <ModelVisual3D> <ModelVisual3D.Content> <DirectionalLight x:name="dirlightmain" Direction="-1,-1,-1"> </DirectionalLight> </ModelVisual3D.Content> </ModelVisual3D> <ModelVisual3D x:name="mymodel"> <ModelVisual3D.Content> <GeometryModel3D> <GeometryModel3D.Geometry> <MeshGeometry3D x:name="meshmain" Positions=" TriangleIndices=" "> </MeshGeometry3D> </GeometryModel3D.Geometry> <GeometryModel3D.Material> <DiffuseMaterial x:name="matdiffusemain"> <DiffuseMaterial.Brush> <SolidColorBrush Color="Bisque"/> </DiffuseMaterial.Brush> 290

298 </DiffuseMaterial> </GeometryModel3D.Material> </GeometryModel3D> </ModelVisual3D.Content> <ModelVisual3D.Transform> <RotateTransform3D> <RotateTransform3D.Rotation> <AxisAngleRotation3D x:name="rotate" Axis="1 2 1"/> </RotateTransform3D.Rotation> </RotateTransform3D> </ModelVisual3D.Transform> </ModelVisual3D> </Viewport3D> <Slider Height="23" HorizontalAlignment="Left" Margin="145,271,0,0" Name="slider1" VerticalAlignment="Top" Width="269" Maximum="360" Value="Binding ElementName=rotate, Path=Angle" /> </Grid> </Window> When you run your application, it will produce a 3D object and a slider on your window. 291

299 When you slide the slider, the object on your window will also rotate. We recommend that you execute the above code and try more 3D geometry. 292

300 49. WPF MULTIMEDIA WPF WPF applications support video and audio using MediaElement. It allows you to integrate audio and video into an application. The MediaElement class works in a similar way as Image class. You just point it at the media and it renders it. The main difference is that it will be a moving image, but if you point it to the file that contains just audio and no video such as an MP3, it will play that without showing anything on the screen. WPF supports all types of video/audio format depending on the machine configuration. If a media file plays a Media Player, it will also work in WPF on the same machine. Example Let s take an example to understand how to integrate multimedia in your application. Create a new WPF project with the name WPFMultimedia. The following XAML code creates a media element and three buttons, and initializes them with some properties. <Window x:class="wpfmultimedia.mainwindow" xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpfmultimedia" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <Grid> <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center"> <MediaElement Name="myMedia" Source="D:\MicrosoftMVA.mp4" LoadedBehavior="Manual" Width="591" Height="274" /> <StackPanel Orientation="Horizontal" Margin="0,10,0,0"> <Button Content="Play" Margin="0,0,10,0" Padding="5" Click="mediaPlay" /> <Button Content="Pause" Margin="0,0,10,0" Padding="5" Click="mediaPause" /> <Button x:name="mutebutt" Content="Mute" Padding="5" Click="mediaMute" /> </StackPanel> </StackPanel> 293

301 </Grid> </Window> Here is the Click events implementation in C# for different buttons. using System; using System.Windows; namespace WPFMultimedia public partial class MainWindow : Window public MainWindow() InitializeComponent(); mymedia.volume = 100; mymedia.play(); void mediaplay(object sender, EventArgs e) mymedia.play(); void mediapause(object sender, EventArgs e) mymedia.pause(); void mediamute(object sender, EventArgs e) if (mymedia.volume == 100) mymedia.volume = 0; mutebutt.content = "Listen"; else mymedia.volume = 100; 294

302 mutebutt.content = "Mute"; When you compile and execute the above code, it will produce the following window. You can play the video and control its playback with the three buttons. With the buttons you can pause, mute, and play the video. Speech Synthesizer WPF has features to convert text to speech. This API is included in System.Speech namespace. SpeechSynthesizer class transforms text into spoken words. Example Let s have a look at a simple example. 1. Create a new WPF project with the name WPFTextToSpeech. 2. We will need System.Speech assembly to add as reference for SpeechSynthesizer class to work. 3. Right click on References and Select Add Reference. 295

303 4. Reference Manager dialog will open. Now check the System.Speech check box 296

304 5. Click the Ok button. You can see the System.Speech assembly in your References. 6. Now drag a button and a textbox into the design window from the toolbox. 7. The following XAML code creates a button and a textbox, and initializes them with some properties. <Window x:class="wpftexttospeech.mainwindow" <Grid> xmlns=" xmlns:x=" xmlns:d=" xmlns:mc=" xmlns:local="clr-namespace:wpftexttospeech" mc:ignorable="d" Title="MainWindow" Height="350" Width="604"> <Button x:name="button" Content="Speak" HorizontalAlignment="Left" Margin="218,176,0,0" VerticalAlignment="Top" Width="75"/> 297

ComponentOne. Windows for WPF

ComponentOne. Windows for WPF ComponentOne Windows for WPF Copyright 1987-2012 GrapeCity, Inc. All rights reserved. ComponentOne, a division of GrapeCity 201 South Highland Avenue, Third Floor Pittsburgh, PA 15206 USA Internet: info@componentone.com

More information

1. WPF Tutorial Page 1 of 431 wpf-tutorial.com

1. WPF Tutorial Page 1 of 431 wpf-tutorial.com 1. WPF Tutorial Page 1 of 431 1.1. About WPF 1.1.1. What is WPF? WPF, which stands for Windows Presentation Foundation, is Microsoft's latest approach to a GUI framework, used with the.net framework. But

More information

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Windows 10 Apps Development

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer. Windows 10 Apps Development About the Tutorial Welcome to Windows 10 tutorial. This tutorial is designed for people who want to learn how to develop apps meant for Windows 10. After completing it, you will have a better understating

More information

wpf5concat Start Microsoft Visual Studio. File New Project WPF Application, Name= wpf5concat OK.

wpf5concat Start Microsoft Visual Studio. File New Project WPF Application, Name= wpf5concat OK. Start Microsoft Visual Studio. wpf5concat File New Project WPF Application, Name= wpf5concat OK. The Solution Explorer displays: Solution wpf5concat, wpf5concat, Properties, References, App.xaml, MainWindow.xaml.

More information

Windows Presentation Foundation Using C#

Windows Presentation Foundation Using C# Windows Presentation Foundation Using C# Student Guide Revision 4.0 Object Innovations Course 4135 Windows Presentation Foundation Using C# Rev. 4.0 Student Guide Information in this document is subject

More information

Introduction to C#, Visual Studio and Windows Presentation Foundation

Introduction to C#, Visual Studio and Windows Presentation Foundation Introduction to C#, Visual Studio and Windows Presentation Foundation Lecture #3: C#, Visual Studio, and WPF Joseph J. LaViola Jr. Fall 2008 Fall 2008 CAP 6938 Topics in Pen-Based User Interfaces Joseph

More information

Hands-On Lab. Building a Data-Driven Master/Detail Business Form using Visual Studio 2010. Lab version: 1.0.0. Last updated: 12/10/2010.

Hands-On Lab. Building a Data-Driven Master/Detail Business Form using Visual Studio 2010. Lab version: 1.0.0. Last updated: 12/10/2010. Hands-On Lab Building a Data-Driven Master/Detail Business Form using Visual Studio 2010 Lab version: 1.0.0 Last updated: 12/10/2010 Page 1 CONTENTS OVERVIEW... 3 EXERCISE 1: CREATING THE APPLICATION S

More information

Understanding In and Out of XAML in WPF

Understanding In and Out of XAML in WPF Understanding In and Out of XAML in WPF 1. What is XAML? Extensible Application Markup Language and pronounced zammel is a markup language used to instantiate.net objects. Although XAML is a technology

More information

Windows Presentation Foundation

Windows Presentation Foundation Windows Presentation Foundation C# Programming April 18 Windows Presentation Foundation WPF (code-named Avalon ) is the graphical subsystem of the.net 3.0 Framework It provides a new unified way to develop

More information

Windows Presentation Foundation Tutorial 1

Windows Presentation Foundation Tutorial 1 Windows Presentation Foundation Tutorial 1 PDF: Tutorial: A http://billdotnet.com/wpf.pdf http://billdotnet.com/dotnet_lecture/dotnet_lecture.htm Introduction 1. Start Visual Studio 2008, and select a

More information

Windows Store App Development

Windows Store App Development Windows Store App Development C# AND XAML PETE BROWN 11 MANNING SHELTER ISLAND contents preface xvii acknowledgments xx about this book xxii about the author xxviii. about the cover illustration xxix If

More information

Microsoft Virtual Labs. Building Windows Presentation Foundation Applications - C# - Part 1

Microsoft Virtual Labs. Building Windows Presentation Foundation Applications - C# - Part 1 Microsoft Virtual Labs Building Windows Presentation Foundation Applications - C# - Part 1 Table of Contents Building Windows Presentation Foundation Applications - C# - Part 1... 1 Exercise 1 Creating

More information

Windows Presentation Foundation (WPF)

Windows Presentation Foundation (WPF) 50151 - Version: 4 05 July 2016 Windows Presentation Foundation (WPF) Windows Presentation Foundation (WPF) 50151 - Version: 4 5 days Course Description: This five-day instructor-led course provides students

More information

Chapter 14 WCF Client WPF Implementation. Screen Layout

Chapter 14 WCF Client WPF Implementation. Screen Layout Chapter 14 WCF Client WPF Implementation Screen Layout Window1.xaml

More information

Implementing multi-user multi-touch scenarios using WPF in Windows* 8 Desktop Apps

Implementing multi-user multi-touch scenarios using WPF in Windows* 8 Desktop Apps Implementing multi-user multi-touch scenarios using WPF in Windows* 8 Desktop Apps Summary In this paper we walk through a sample application (in this case a game that quizzes people on the Periodic Table)

More information

Top 50 WPF Interview Questions

Top 50 WPF Interview Questions Top 50 WPF Interview Questions 1. What is WPF? WPF is the latest presentation API by Microsoft Windows. It is 2D and 3D graphic engine. Its capabilities include:- All the common user controls. For example,

More information

WPF Shapes. WPF Shapes, Canvas, Dialogs 1

WPF Shapes. WPF Shapes, Canvas, Dialogs 1 WPF Shapes WPF Shapes, Canvas, Dialogs 1 Shapes are elements WPF Shapes, Canvas, Dialogs 2 Shapes draw themselves, no invalidation or repainting needed when shape moves, window is resized, or shape s properties

More information

WPF Learner s Guide to Head First C#

WPF Learner s Guide to Head First C# Good news! I just approved your request to upgrade your desktop to Windows 2003. There are many projects in Head First C# where you build Windows Store apps that require Windows 8. In this appendix, you'll

More information

STEP BY STEP to Build the Application 1. Start a. Open a MvvmLight (WPF4) application and name it MvvmControlChange.

STEP BY STEP to Build the Application 1. Start a. Open a MvvmLight (WPF4) application and name it MvvmControlChange. Application Description This MVVM WPF application includes a WPF Window with a contentcontrol and multiple UserControls the user can navigate between with button controls. The contentcontrols will have

More information

Mapping to the Windows Presentation Framework

Mapping to the Windows Presentation Framework Mapping to the Windows Presentation Framework This section maps the main IFML concepts to the.net Windows Presentation Framework (WFP). Windows Presentation Framework (WPF) is a part of.net Framework by

More information

How to Develop Accessible Linux Applications

How to Develop Accessible Linux Applications Sharon Snider Copyright 2002 by IBM Corporation v1.1, 2002 05 03 Revision History Revision v1.1 2002 05 03 Revised by: sds Converted to DocBook XML and updated broken links. Revision v1.0 2002 01 28 Revised

More information

Word basics. Before you begin. What you'll learn. Requirements. Estimated time to complete:

Word basics. Before you begin. What you'll learn. Requirements. Estimated time to complete: Word basics Word is a powerful word processing and layout application, but to use it most effectively, you first have to understand the basics. This tutorial introduces some of the tasks and features that

More information

Hypercosm. Studio. www.hypercosm.com

Hypercosm. Studio. www.hypercosm.com Hypercosm Studio www.hypercosm.com Hypercosm Studio Guide 3 Revision: November 2005 Copyright 2005 Hypercosm LLC All rights reserved. Hypercosm, OMAR, Hypercosm 3D Player, and Hypercosm Studio are trademarks

More information

SAS BI Dashboard 4.3. User's Guide. SAS Documentation

SAS BI Dashboard 4.3. User's Guide. SAS Documentation SAS BI Dashboard 4.3 User's Guide SAS Documentation The correct bibliographic citation for this manual is as follows: SAS Institute Inc. 2010. SAS BI Dashboard 4.3: User s Guide. Cary, NC: SAS Institute

More information

Important New Concepts in WPF

Important New Concepts in WPF CHAPTER 3 Important New Concepts in WPF IN THIS CHAPTER. Logical and Visual Trees. Dependency Properties. Routed Events. Commands. A Tour of the Class Hierarchy To finish Part I of this book, and before

More information

Agenda2. User Manual. Agenda2 User Manual Copyright 2010-2013 Bobsoft 1 of 34

Agenda2. User Manual. Agenda2 User Manual Copyright 2010-2013 Bobsoft 1 of 34 Agenda2 User Manual Agenda2 User Manual Copyright 2010-2013 Bobsoft 1 of 34 Agenda2 User Manual Copyright 2010-2013 Bobsoft 2 of 34 Contents 1. User Interface! 5 2. Quick Start! 6 3. Creating an agenda!

More information

Tutorial: Building a Dojo Application using IBM Rational Application Developer Loan Payment Calculator

Tutorial: Building a Dojo Application using IBM Rational Application Developer Loan Payment Calculator Tutorial: Building a Dojo Application using IBM Rational Application Developer Loan Payment Calculator Written by: Chris Jaun (cmjaun@us.ibm.com) Sudha Piddaparti (sudhap@us.ibm.com) Objective In this

More information

Relationships in WPF Applications

Relationships in WPF Applications Chapter 15 Relationships in WPF Applications Table of Contents Chapter 15... 15-1 Relationships in WPF Applications... 15-1 One-To-Many Combo Box to List Box... 15-1 One-To-Many Relationships using Properties...

More information

Microsoft PowerPoint 2010 Handout

Microsoft PowerPoint 2010 Handout Microsoft PowerPoint 2010 Handout PowerPoint is a presentation software program that is part of the Microsoft Office package. This program helps you to enhance your oral presentation and keep the audience

More information

CaptainCasa. CaptainCasa Enterprise Client. CaptainCasa Enterprise Client. Feature Overview

CaptainCasa. CaptainCasa Enterprise Client. CaptainCasa Enterprise Client. Feature Overview Feature Overview Page 1 Technology Client Server Client-Server Communication Client Runtime Application Deployment Java Swing based (JRE 1.6), generic rich frontend client. HTML based thin frontend client

More information

Excel 2007 Basic knowledge

Excel 2007 Basic knowledge Ribbon menu The Ribbon menu system with tabs for various Excel commands. This Ribbon system replaces the traditional menus used with Excel 2003. Above the Ribbon in the upper-left corner is the Microsoft

More information

SQL Server 2005: Report Builder

SQL Server 2005: Report Builder SQL Server 2005: Report Builder Table of Contents SQL Server 2005: Report Builder...3 Lab Setup...4 Exercise 1 Report Model Projects...5 Exercise 2 Create a Report using Report Builder...9 SQL Server 2005:

More information

Windows Presentation Foundation: What, Why and When

Windows Presentation Foundation: What, Why and When Windows Presentation Foundation: What, Why and When A. WHY WPF: WPF is framework to build application for windows. It is designed for.net influenced by modern display technologies like HTML and Flash and

More information

Microsoft Office PowerPoint 2013

Microsoft Office PowerPoint 2013 Microsoft Office PowerPoint 2013 Navigating the PowerPoint 2013 Environment The Ribbon: The ribbon is where you will access a majority of the commands you will use to create and develop your presentation.

More information

M-Files Gantt View. User Guide. App Version: 1.1.0 Author: Joel Heinrich

M-Files Gantt View. User Guide. App Version: 1.1.0 Author: Joel Heinrich M-Files Gantt View User Guide App Version: 1.1.0 Author: Joel Heinrich Date: 02-Jan-2013 Contents 1 Introduction... 1 1.1 Requirements... 1 2 Basic Use... 1 2.1 Activation... 1 2.2 Layout... 1 2.3 Navigation...

More information

Sample Table. Columns. Column 1 Column 2 Column 3 Row 1 Cell 1 Cell 2 Cell 3 Row 2 Cell 4 Cell 5 Cell 6 Row 3 Cell 7 Cell 8 Cell 9.

Sample Table. Columns. Column 1 Column 2 Column 3 Row 1 Cell 1 Cell 2 Cell 3 Row 2 Cell 4 Cell 5 Cell 6 Row 3 Cell 7 Cell 8 Cell 9. Working with Tables in Microsoft Word The purpose of this document is to lead you through the steps of creating, editing and deleting tables and parts of tables. This document follows a tutorial format

More information

Create a Google Site in DonsApp

Create a Google Site in DonsApp Create a Google Site in DonsApp 1 Google Web Site Interactive. Constructivist. Collaborative. Communities. WHAT IS GOOGLE SITE? With one single click, you can create a website without any knowledge of

More information

Nintex Forms 2013 Help

Nintex Forms 2013 Help Nintex Forms 2013 Help Last updated: Friday, April 17, 2015 1 Administration and Configuration 1.1 Licensing settings 1.2 Activating Nintex Forms 1.3 Web Application activation settings 1.4 Manage device

More information

1. WPF Tutorial Page 1 of 359 wpf-tutorial.com

1. WPF Tutorial Page 1 of 359 wpf-tutorial.com 1. WPF Tutorial Page 1 of 359 1.1. About WPF 1.1.1. What is WPF? WPF, which stands for Windows Presentation Foundation, is Microsoft's latest approach to a GUI framework, used with the.net framework. But

More information

App Development for Modern UI MODULE 4: APP DEVELOPMENT ESSENTIALS

App Development for Modern UI MODULE 4: APP DEVELOPMENT ESSENTIALS App Development for Modern UI MODULE 4: APP DEVELOPMENT ESSENTIALS Module 4: App Development Essentials Windows, Bing, PowerPoint, Internet Explorer, Visual Studio, WebMatrix, DreamSpark, and Silverlight

More information

Logi Ad Hoc Reporting System Administration Guide

Logi Ad Hoc Reporting System Administration Guide Logi Ad Hoc Reporting System Administration Guide Version 11.2 Last Updated: March 2014 Page 2 Table of Contents INTRODUCTION... 4 Target Audience... 4 Application Architecture... 5 Document Overview...

More information

Visual Studio 2008: Windows Presentation Foundation

Visual Studio 2008: Windows Presentation Foundation Visual Studio 2008: Windows Presentation Foundation Course 6460A: Three days; Instructor-Led Introduction This three-day instructor-led course provides students with the knowledge and skills to build and

More information

Application Developer Guide

Application Developer Guide IBM Maximo Asset Management 7.1 IBM Tivoli Asset Management for IT 7.1 IBM Tivoli Change and Configuration Management Database 7.1.1 IBM Tivoli Service Request Manager 7.1 Application Developer Guide Note

More information

3 IDE (Integrated Development Environment)

3 IDE (Integrated Development Environment) Visual C++ 6.0 Guide Part I 1 Introduction Microsoft Visual C++ is a software application used to write other applications in C++/C. It is a member of the Microsoft Visual Studio development tools suite,

More information

Microsoft PowerPoint Tutorial

Microsoft PowerPoint Tutorial Microsoft PowerPoint Tutorial Contents Starting MS PowerPoint... 1 The MS PowerPoint Window... 2 Title Bar...2 Office Button...3 Saving Your Work... 3 For the first time... 3 While you work... 3 Backing

More information

Data Tool Platform SQL Development Tools

Data Tool Platform SQL Development Tools Data Tool Platform SQL Development Tools ekapner Contents Setting SQL Development Preferences...5 Execution Plan View Options Preferences...5 General Preferences...5 Label Decorations Preferences...6

More information

Data Binding with WPF: Binding to XML

Data Binding with WPF: Binding to XML Data Binding with WPF: Binding to XML Excerpted from WPF in Action with Visual Studio 2008 EARLY ACCESS EDITION Arlen Feldman and Maxx Daymon MEAP Release: July 2007 Softbound print: October 2008 (est.),

More information

Content Author's Reference and Cookbook

Content Author's Reference and Cookbook Sitecore CMS 6.5 Content Author's Reference and Cookbook Rev. 110621 Sitecore CMS 6.5 Content Author's Reference and Cookbook A Conceptual Overview and Practical Guide to Using Sitecore Table of Contents

More information

Windows Presentation Foundation (WPF) User Interfaces

Windows Presentation Foundation (WPF) User Interfaces Windows Presentation Foundation (WPF) User Interfaces Rob Miles Department of Computer Science 29c 08120 Programming 2 Design Style and programming As programmers we probably start of just worrying about

More information

Microsoft FrontPage 2003

Microsoft FrontPage 2003 Information Technology Services Kennesaw State University Microsoft FrontPage 2003 Information Technology Services Microsoft FrontPage Table of Contents Information Technology Services...1 Kennesaw State

More information

Introduction to Application Development with Silverlight for Windows Embedded. Abstract. Windows Embedded CE 6.0 R3 Technical Article

Introduction to Application Development with Silverlight for Windows Embedded. Abstract. Windows Embedded CE 6.0 R3 Technical Article Introduction to Application Development with Silverlight for Windows Embedded Windows Embedded CE 6.0 R3 Technical Article Writers: David Franklin Published: September 2009 Applies To: Windows Embedded

More information

Teradata SQL Assistant Version 13.0 (.Net) Enhancements and Differences. Mike Dempsey

Teradata SQL Assistant Version 13.0 (.Net) Enhancements and Differences. Mike Dempsey Teradata SQL Assistant Version 13.0 (.Net) Enhancements and Differences by Mike Dempsey Overview SQL Assistant 13.0 is an entirely new application that has been re-designed from the ground up. It has been

More information

Bitrix Site Manager 4.1. User Guide

Bitrix Site Manager 4.1. User Guide Bitrix Site Manager 4.1 User Guide 2 Contents REGISTRATION AND AUTHORISATION...3 SITE SECTIONS...5 Creating a section...6 Changing the section properties...8 SITE PAGES...9 Creating a page...10 Editing

More information

BUILDING APPLICATIONS USING C# AND.NET FRAMEWORK (OBJECT-ORIENTED PROGRAMMING, X428.6)

BUILDING APPLICATIONS USING C# AND.NET FRAMEWORK (OBJECT-ORIENTED PROGRAMMING, X428.6) Technology & Information Management Instructor: Michael Kremer, Ph.D. Class 9 Professional Program: Data Administration and Management BUILDING APPLICATIONS USING C# AND.NET FRAMEWORK (OBJECT-ORIENTED

More information

Writer Guide. Chapter 15 Using Forms in Writer

Writer Guide. Chapter 15 Using Forms in Writer Writer Guide Chapter 15 Using Forms in Writer Copyright This document is Copyright 2005 2008 by its contributors as listed in the section titled Authors. You may distribute it and/or modify it under the

More information

Advanced Presentation Features and Animation

Advanced Presentation Features and Animation There are three features that you should remember as you work within PowerPoint 2007: the Microsoft Office Button, the Quick Access Toolbar, and the Ribbon. The function of these features will be more

More information

آموزش DataGrid در WPF به همراه صفحه بندي و جستجوي انتخابی. کلیک کن www.papro-co.ir

آموزش DataGrid در WPF به همراه صفحه بندي و جستجوي انتخابی. کلیک کن www.papro-co.ir آموزش DataGrid در WPF به همراه صفحه بندي و جستجوي انتخابی در پاپرو برنامه نویسی را شیرین یاد بگیرید کلیک کن www.papro-co.ir WPF DataGrid Custom Paging and Sorting This article shows how to implement custom

More information

Macros in Word & Excel

Macros in Word & Excel Macros in Word & Excel Description: If you perform a task repeatedly in Word or Excel, you can automate the task by using a macro. A macro is a series of steps that is grouped together as a single step

More information

Microsoft Word 2010. Quick Reference Guide. Union Institute & University

Microsoft Word 2010. Quick Reference Guide. Union Institute & University Microsoft Word 2010 Quick Reference Guide Union Institute & University Contents Using Word Help (F1)... 4 Window Contents:... 4 File tab... 4 Quick Access Toolbar... 5 Backstage View... 5 The Ribbon...

More information

How to create and personalize a PDF portfolio

How to create and personalize a PDF portfolio How to create and personalize a PDF portfolio Creating and organizing a PDF portfolio is a simple process as simple as dragging and dropping files from one folder to another. To drag files into an empty

More information

Overview of Microsoft Office Word 2007

Overview of Microsoft Office Word 2007 Overview of Microsoft Office What Is Word Processing? Office is a word processing software application whose purpose is to help you create any type of written communication. A word processor can be used

More information

Please select one of the topics below.

Please select one of the topics below. Thanks for choosing WYSIWYG Web Builder! In this section we will give a short introduction to Web Builder so you can start building your web site in (almost) no time. Please select one of the topics below.

More information

Modifier with Visual Basic with Applications (VBA) in Microsoft Dynamics GP 9.0

Modifier with Visual Basic with Applications (VBA) in Microsoft Dynamics GP 9.0 Modifier with Visual Basic with Applications (VBA) in Microsoft Dynamics GP 9.0 8520: Modifier with VBA in Microsoft Dynamics GP 9.0 (3 Days) About this Course The three-day Microsoft DynamicsT GP Modifier

More information

Windows Phone 7 Mobile Applications Using Decision Structures

Windows Phone 7 Mobile Applications Using Decision Structures C7937_ch05_rev03_001-086.qxd 7/11/11 10:07 AM Page 1 CHAPTER 5 Windows Phone 7 Mobile Applications Using Decision Structures OBJECTIVES Write a program for the Windows Phone 7 development platform Understand

More information

Creating Interactive PDF Forms

Creating Interactive PDF Forms Creating Interactive PDF Forms Using Adobe Acrobat X Pro Information Technology Services Outreach and Distance Learning Technologies Copyright 2012 KSU Department of Information Technology Services This

More information

APPLICATION NOTE. Atmel AVR10006: XDK User Guide. Atmel Microcontrollers. Features. Description

APPLICATION NOTE. Atmel AVR10006: XDK User Guide. Atmel Microcontrollers. Features. Description APPLICATION NOTE Atmel AVR10006: XDK User Guide Atmel Microcontrollers Features Extension Developer s Kit user guide Generate and publish an Atmel Studio extension Atmel Studio IDE SDK Embedded SDK Description

More information

Microsoft Publisher 2010 What s New!

Microsoft Publisher 2010 What s New! Microsoft Publisher 2010 What s New! INTRODUCTION Microsoft Publisher 2010 is a desktop publishing program used to create professional looking publications and communication materials for print. A new

More information

MS Word 2007 practical notes

MS Word 2007 practical notes MS Word 2007 practical notes Contents Opening Microsoft Word 2007 in the practical room... 4 Screen Layout... 4 The Microsoft Office Button... 4 The Ribbon... 5 Quick Access Toolbar... 5 Moving in the

More information

Building and Using Web Services With JDeveloper 11g

Building and Using Web Services With JDeveloper 11g Building and Using Web Services With JDeveloper 11g Purpose In this tutorial, you create a series of simple web service scenarios in JDeveloper. This is intended as a light introduction to some of the

More information

Sitecore InDesign Connector 1.1

Sitecore InDesign Connector 1.1 Sitecore Adaptive Print Studio Sitecore InDesign Connector 1.1 - User Manual, October 2, 2012 Sitecore InDesign Connector 1.1 User Manual Creating InDesign Documents with Sitecore CMS User Manual Page

More information

About XML in InDesign

About XML in InDesign 1 Adobe InDesign 2.0 Extensible Markup Language (XML) is a text file format that lets you reuse content text, table data, and graphics in a variety of applications and media. One advantage of using XML

More information

Chapter 15 Using Forms in Writer

Chapter 15 Using Forms in Writer Writer Guide Chapter 15 Using Forms in Writer OpenOffice.org Copyright This document is Copyright 2005 2006 by its contributors as listed in the section titled Authors. You can distribute it and/or modify

More information

Customizing forms and writing QuickBooks Letters

Customizing forms and writing QuickBooks Letters LESSON 15 Customizing forms and writing QuickBooks Letters 15 Lesson objectives, 398 Supporting materials, 398 Instructor preparation, 398 To start this lesson, 398 About QuickBooks forms, 399 Customizing

More information

Dreamweaver CS4 Day 2 Creating a Website using Div Tags, CSS, and Templates

Dreamweaver CS4 Day 2 Creating a Website using Div Tags, CSS, and Templates Dreamweaver CS4 Day 2 Creating a Website using Div Tags, CSS, and Templates What is a DIV tag? First, let s recall that HTML is a markup language. Markup provides structure and order to a page. For example,

More information

Microsoft Word 2010 Tutorial

Microsoft Word 2010 Tutorial 1 Microsoft Word 2010 Tutorial Microsoft Word 2010 is a word-processing program, designed to help you create professional-quality documents. With the finest documentformatting tools, Word helps you organize

More information

Building A Very Simple Website

Building A Very Simple Website Sitecore CMS 6.5 Building A Very Simple Web Site Rev 110715 Sitecore CMS 6.5 Building A Very Simple Website A Self-Study Guide for Developers Table of Contents Chapter 1 Introduction... 3 Chapter 2 Creating

More information

Introduction to Microsoft Word 2003

Introduction to Microsoft Word 2003 Introduction to Microsoft Word 2003 Sabeera Kulkarni Information Technology Lab School of Information University of Texas at Austin Fall 2004 1. Objective This tutorial is designed for users who are new

More information

Microsoft Word 2010 Prepared by Computing Services at the Eastman School of Music July 2010

Microsoft Word 2010 Prepared by Computing Services at the Eastman School of Music July 2010 Microsoft Word 2010 Prepared by Computing Services at the Eastman School of Music July 2010 Contents Microsoft Office Interface... 4 File Ribbon Tab... 5 Microsoft Office Quick Access Toolbar... 6 Appearance

More information

Android Studio Application Development

Android Studio Application Development Android Studio Application Development Belén Cruz Zapata Chapter No. 4 "Using the Code Editor" In this package, you will find: A Biography of the author of the book A preview chapter from the book, Chapter

More information

Creating a Web Service using IBM Rational HATS. For IBM System i (5250) Creating a Web Service using HATS 1

Creating a Web Service using IBM Rational HATS. For IBM System i (5250) Creating a Web Service using HATS 1 Creating a Web Service using IBM Rational HATS For IBM System i (5250) Creating a Web Service using HATS 1 Lab instructions This lab teaches you how to use IBM Rational HATS to create a Web service that

More information

Building A Very Simple Web Site

Building A Very Simple Web Site Sitecore CMS 6.2 Building A Very Simple Web Site Rev 100601 Sitecore CMS 6. 2 Building A Very Simple Web Site A Self-Study Guide for Developers Table of Contents Chapter 1 Introduction... 3 Chapter 2 Building

More information

BIGPOND ONLINE STORAGE USER GUIDE Issue 1.1.0-18 August 2005

BIGPOND ONLINE STORAGE USER GUIDE Issue 1.1.0-18 August 2005 BIGPOND ONLINE STORAGE USER GUIDE Issue 1.1.0-18 August 2005 PLEASE NOTE: The contents of this publication, and any associated documentation provided to you, must not be disclosed to any third party without

More information

Excel 2007: Basics Learning Guide

Excel 2007: Basics Learning Guide Excel 2007: Basics Learning Guide Exploring Excel At first glance, the new Excel 2007 interface may seem a bit unsettling, with fat bands called Ribbons replacing cascading text menus and task bars. This

More information

Contents. Microsoft Office 2010 Tutorial... 1

Contents. Microsoft Office 2010 Tutorial... 1 Microsoft Office 2010 Tutorial Contents Microsoft Office 2010 Tutorial... 1 Find your way through long documents with the new Document Navigation pane and Search... 4 Adjust the spaces between lines or

More information

Kentico CMS, 2011 Kentico Software. Contents. Mobile Development using Kentico CMS 6 2 Exploring the Mobile Environment 1

Kentico CMS, 2011 Kentico Software. Contents. Mobile Development using Kentico CMS 6 2 Exploring the Mobile Environment 1 Contents Mobile Development using Kentico CMS 6 2 Exploring the Mobile Environment 1 Time for action - Viewing the mobile sample site 2 What just happened 4 Time for Action - Mobile device redirection

More information

Creating Web Pages with Microsoft FrontPage

Creating Web Pages with Microsoft FrontPage Creating Web Pages with Microsoft FrontPage 1. Page Properties 1.1 Basic page information Choose File Properties. Type the name of the Title of the page, for example Template. And then click OK. Short

More information

Dreamweaver CS6 Basics

Dreamweaver CS6 Basics Dreamweaver CS6 Basics Learn the basics of building an HTML document using Adobe Dreamweaver by creating a new page and inserting common HTML elements using the WYSIWYG interface. EdShare EdShare is a

More information

Acrobat X Pro Accessible Forms and Interactive Documents

Acrobat X Pro Accessible Forms and Interactive Documents Contents 2 PDF Form Fields 2 Acrobat Form Wizard 5 Enter Forms Editing Mode Directly 5 Create Form Fields Manually 6 Forms Editing Mode 8 Form Field Properties 11 Editing or Modifying an Existing Form

More information

Microsoft Excel 2010 Part 3: Advanced Excel

Microsoft Excel 2010 Part 3: Advanced Excel CALIFORNIA STATE UNIVERSITY, LOS ANGELES INFORMATION TECHNOLOGY SERVICES Microsoft Excel 2010 Part 3: Advanced Excel Winter 2015, Version 1.0 Table of Contents Introduction...2 Sorting Data...2 Sorting

More information

Acrobat X Pro PDF Accessibility Repair Workflow

Acrobat X Pro PDF Accessibility Repair Workflow Contents 2 Step 1: Examine the PDF File 2 Step 2: Determine if the PDF is a Scanned Document 6 Step 3: Add Interactive Features: Form Fields and Buttons 19 Step 4: Add Other Accessibility Features 23 Step

More information

USER GUIDE. Unit 2: Synergy. Chapter 2: Using Schoolwires Synergy

USER GUIDE. Unit 2: Synergy. Chapter 2: Using Schoolwires Synergy USER GUIDE Unit 2: Synergy Chapter 2: Using Schoolwires Synergy Schoolwires Synergy & Assist Version 2.0 TABLE OF CONTENTS Introductions... 1 Audience... 1 Objectives... 1 Before You Begin... 1 Getting

More information

Introduction to dobe Acrobat XI Pro

Introduction to dobe Acrobat XI Pro Introduction to dobe Acrobat XI Pro Introduction to Adobe Acrobat XI Pro is licensed under the Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License. To view a copy of this

More information

I ntroduction. Accessing Microsoft PowerPoint. Anatomy of a PowerPoint Window

I ntroduction. Accessing Microsoft PowerPoint. Anatomy of a PowerPoint Window Accessing Microsoft PowerPoint To access Microsoft PowerPoint from your home computer, you will probably either use the Start menu to select the program or double-click on an icon on the Desktop. To open

More information

Name of chapter & details

Name of chapter & details Course Title Course Code Modern Application Development CE913 (Elective III) Theory : 03 Course Credit Practical : 01 Tutorial : 00 Course Learning Outcomes Credits : 04 On the completion of the course,

More information

PowerPoint 2007 Basics Website: http://etc.usf.edu/te/

PowerPoint 2007 Basics Website: http://etc.usf.edu/te/ Website: http://etc.usf.edu/te/ PowerPoint is the presentation program included in the Microsoft Office suite. With PowerPoint, you can create engaging presentations that can be presented in person, online,

More information

Bookstore Application: Client Tier

Bookstore Application: Client Tier 29 T U T O R I A L Objectives In this tutorial, you will learn to: Create an ASP.NET Web Application project. Create and design ASPX pages. Use Web Form controls. Reposition controls, using the style attribute.

More information

During the process of creating ColorSwitch, you will learn how to do these tasks:

During the process of creating ColorSwitch, you will learn how to do these tasks: GUI Building in NetBeans IDE 3.6 This short tutorial guides you through the process of creating an application called ColorSwitch. You will build a simple program that enables you to switch the color of

More information

DOING MORE WITH WORD: MICROSOFT OFFICE 2010

DOING MORE WITH WORD: MICROSOFT OFFICE 2010 University of North Carolina at Chapel Hill Libraries Carrboro Cybrary Chapel Hill Public Library Durham County Public Library DOING MORE WITH WORD: MICROSOFT OFFICE 2010 GETTING STARTED PAGE 02 Prerequisites

More information

Dreamweaver. Introduction to Editing Web Pages

Dreamweaver. Introduction to Editing Web Pages Dreamweaver Introduction to Editing Web Pages WORKSHOP DESCRIPTION... 1 Overview 1 Prerequisites 1 Objectives 1 INTRODUCTION TO DREAMWEAVER... 1 Document Window 3 Toolbar 3 Insert Panel 4 Properties Panel

More information

Handout: Word 2010 Tips and Shortcuts

Handout: Word 2010 Tips and Shortcuts Word 2010: Tips and Shortcuts Table of Contents EXPORT A CUSTOMIZED QUICK ACCESS TOOLBAR... 2 IMPORT A CUSTOMIZED QUICK ACCESS TOOLBAR... 2 USE THE FORMAT PAINTER... 3 REPEAT THE LAST ACTION... 3 SHOW

More information