Creating a WPF application
-
- Windows and navigation applications are installed on a desktop computer. These applications can also run under the full trust environment and have full access to the resources of the computer being used.
- A XAML browser application runs in Windows Internet Explorer. It runs under a limited set of permissions allowed by the Internet security zone. It can access isolated storage available in the zone. It cannot use a desktop computer’s resources such as the file system, databases, and the Windows registry.
- A WPF standalone application is installed on a client computer. Hence, it does not require a Web browser. It behaves like a Windows Form application and presents a non-navigational interface to a user. It can also be used by offline users.
- The WPF technology supports three basic types of applications, namely Windows applications, navigation applications, and XAML browser applications.
- A WPF application supports Web-style navigation capabilities using Web pages and hyperlinks.
- The event route for a particular event (for example, the Click event) can travel from the source element, which bubbles upwards through the element tree of its parent element until it reaches the element tree root (can be a page or a window).
- The Click event is raised when the Button control is clicked.
- The private void OnChildElementMouseDown(object sender, MouseButtonEventArgs e) {} code segment in the scenario will simply execute the mouse event and the bubbling or tunneling routing process will continue. If you have written e.Handled = true; inside the code statement, the bubbling or tunneling routing process would have been stopped and has marked the event as handled in the event handler.
Pass MCTS: Microsoft Visual Studio 2008 in a first attempt:
-
- 70-502-CSHARP, MCTS: C# .NET 3.5 C# Windows Presentation Foundation Application Development
- 70-503-CSHARP, MCTS: C#.NET Framework 3.5 – Windows Communication Foundation Application
- 70-504-CSHARP, MCTS:.NET C# 3.5 – Windows Workflow Foundation Application Development
- 70-536-CSHARP, C# .NET Framework Application Development Foundation
- 70-561-CSHARP, TS: Microsoft .NET Framework 3.5, ADO.NET Application Development
- The Click event occurs when a Button is clicked, and the MouseEnter event occurs when the mouse pointer enters the bounds of an element.
- The following are the steps to create a custom routed event in correct order:
- Register an instance of the RoutedEvent class.
- Use the RegisterRoutedEvent method of the EventManager class.
- The CommandTarget property of the ICommandSource interface is an object on which the command is executed.
- In order to declare a command on an invoker, the Command property is set on the control (for example, button) that will fire the command.
- The following are the four main concepts of the routed command model in WPF:
- Command
- Command Source
- Command Target
- Command Binding
- To use WPF functionality to your project, you should add System.net namespace to your project file.
- The StartupUri attribute of the tag should be defined, as it indicates the name of the XAML page that should be loaded and displayed when the application is started.
- When an application build is executed, the Build Action property of a file is set indicating how that file is stored within Visual Studio. When the Build Action property of an image file is set to Embedded Resource value, it indicates that the file is embedded in the main project build output as a DLL or executable.
- The Application current = App.Current; code statement creates a reference to the Application object for the current AppDomain. There can be only one instance of the Application class per AppDomain, as the services of the Application class are shared across an application.
- Consider the following code segment: Uri pageUri = new Uri(“/mycontent.xaml”, UriKind.Relative); this.pageFrame.Source = pageUri; This code statement loads a page content file and sets it as the content of a Frame (pageFrame) object.
- The BrowseForward property of the NavigationCommands class represents the Browse Forward command that enables a user to navigate forward to the next page in the application’s journal.
- The BrowseBack property of the NavigationCommands class represents the Browse Back command that enables a user to navigate back to the previous page in the application’s journal.
- A page can have only one child control.
- The Navigate method of the NavigationWindow class navigates asynchronously to the specified source content. The Source property of the NavigationWindow class gets or sets the URI of the current content or the URI of new content that is currently being navigated to.
- The Page class is used to encapsulate a page of content, which can be navigated to and hosted by Windows Internet Explorer, NavigationWindow object, and Frame object.
- The CanGoForward property of the NavigationService class sets a value to true if there is at least one journal entry in the forward navigation history. It sets or gets its value before calling the NavigationService.GoForward method.
- The CanGoBack property of the NavigationService class sets a value to true if there is at least one journal entry in the back navigation history. It sets or gets its value before calling the NavigationService.GoBack method.
- When the NavigationWindow.StopLoading method is called, the NavigationStopped event of the NavigationWindow class is raised. It occurs when a new navigation is requested and a current navigation is in progress.
- The Canvas panel is used to improve the application performance, as it uses the least resources.
- In order to gain better application performance, it is highly recommended to create a reduced-sized version of a thumbnail image.
- If a custom control is used in an application and its resources are defined in a ResourceDictionary object, it is recommended that the application resources be defined at the Application or Window object level or in the default theme for the custom control.
Building user interfaces
- The RowDefinitions property returns one or more RowDefinition elements, and each such element becomes a placeholder representing a row in the final grid layout.
- The Point class defines the position of a window, and the Size class defines the size of the window.
- The element differs from other flow document elements in that it enables a user to dynamically choose between various viewing modes.
- The Thumb control enables a user to perform drag and drop capabilities. It can be included in another control such as ScrollBar or Slider controls so that the user can change the control’s value. It is also used to resize controls. It can receive mouse captures, but cannot receive any keyboard focus.
- The UniformGrid class is used to arrange the contents in a grid in which all the cells in the grid have the same size.
- A element hierarchically organizes elements that are associated with commands and event handlers.
- A sub-element defines a selectable item inside the element.
- The WindowsFormsHost element is used to host Windows Forms controls into the WPF layout system.
- The System.Windows.Forms.Integration namespace contains classes that enable interoperation between Windows Forms and WPF technologies. When both these technologies are interoperated, Windows Forms controls can be hosted on WPF pages and WPF elements in Windows Forms applications.
- The element uses an image as fill color to fill graphics objects such as a rectangle, ellipse, and image path. It defines an image source by using the ImageSource property.
- The control properties are set inside a .xaml file. The Setter property is written in a .xaml file.
- Adding a trigger to the ListBox style will dynamically change the appearance and behavior of the selected item in the ListBox control without creating a new control. A trigger enables a user to change the property values or take actions based on the value of a property.
- The functionality of visual cues to a user and adding functional handles to elements or provide state information about a control can be achieved by creating an instance of the Adorner class. This class can draw ellipses and associate it with a WPF control.
- The CharacterCasing property of the element sets to indicate whether the TextBox control has modified the case of characters as they are typed.
- The CheckBox control enables a user to select and clear. It inherits from the ToggleButton class and can have three states, namely the checked (selected), unchecked (cleared), and indeterminate.
- In Email Support, the mailto:URI is used to open a new mail window that contains an email address, a subject, and a body text.
- A CheckBox control allows three states i.e. the checked (selected), unchecked (cleared), and indeterminate, and a user will have three options to choose with only one mouse click.
- TabControl and Frame are not layout controls but navigation controls.
- The StackPanel panel allows its child elements to be stacked in a specified direction. It allows its content to flow both vertically and horizontally.
- The x:Class attribute in the XAML file causes the Microsoft build engine (MSBuild) to create a partial class for a custom user control.
- A control template is a feature that defines the structure and appearance of a WPF control. This separates the appearance of the control from its functionality. A control’s appearance can be drastically changed by redefining its ControlTemplate object.
- A static resource references from within a resource dictionary of an application.
- A custom control can be created by inheriting from the Control class, the UserControl class, or from an existing Windows Form control.
Pass MCTS: Microsoft Visual Studio 2008 in a first attempt:
- 70-502-CSHARP, MCTS: C# .NET 3.5 C# Windows Presentation Foundation Application Development
- 70-503-CSHARP, MCTS: C#.NET Framework 3.5 – Windows Communication Foundation Application
- 70-504-CSHARP, MCTS:.NET C# 3.5 – Windows Workflow Foundation Application Development
- 70-536-CSHARP, C# .NET Framework Application Development Foundation
- 70-561-CSHARP, TS: Microsoft .NET Framework 3.5, ADO.NET Application Development
Adding and managing content
- To implement an animation simply moving a screen object such as a shape or control from one point on the screen to another, the following actions will best fulfill this requirement:
- Use a Path object and set its data property to the object you wish to move.
- Use a PointAnimation object to move the target object along the path and define the actual movement.
- The following actions should be taken to combine two images and apply an opacity mask to them:
- Firstly, create a DrawingGroup object.
- Secondly, add the two already created images to the DrawingGroup.
- Lastly, define the OpacityMask property and apply it to the DrawingGroup.
- In order to use animations in a button to appear as fade in and out of view, you can use a DoubleAnimation object. The object must be combined with a StoryBoard object in order to associate it with a particular control, i.e. the button.
- The HitTestResult class is used to test for a hit from a given point against objects in the visual tree. It provides the base class for several classes that represent the return value from a hit test.
- To create a utility that will find out which network printers are currently available to print documents, you should take the following steps:
- Obtain a list of all print servers.
- Loop through each print server to query their print queues.
- Examine each printing property that might indicate that the queue is not currently working.
- The following steps should be taken to identify and help diagnose problems in the printing:
- Loop through the print servers to query their print queues.
- Within each pass of the server loop, loop through all the server’s queues to query their jobs, and then loop through the jobs for that server.
- When the problematic print job has been identified, examine relevant properties to see what might be the problem.
- If a WPF application needs to support advanced formatting of text, then you should take the following actions:
- Implement an instance of the TextFormatter class.
- Then, use this instance with an instance of the TextLine class. This will at first format and then draw each line of text.
- MediaElement is a control that is used to present audio, video, and video with audio contents. This control can be usable by different controls both via XAML and code. It can also support layouts for WPF application’s user interface.
- In the XAML tag, the LoadedBehavior property should be set to Manual, as this setting will interactively control media with the Play, Pause, and Stop methods for a MediaElement control. Therefore, a user will be able to stop, pause, and restart the movie file.
- If you want to add audio feedback to several buttons such as a sound that says ‘data saved’ or ‘error encountered’, etc., several sound files will be used, but each will be small, only lasting a few seconds. The simplest way to implement these requirements is to add a trigger to the button, and in that trigger, define a storyboard. In the storyboard, you can then play the sound file.
- Storyboards are used for many types of media and animation playbacks.
- If an application’s resource files need to be available all the time to the application, then the files should be compiled into the application’s main executable assembly or one of its referenced assemblies.
- An and a tag for each separate XAML file will be included as page items. Since they do have code behind files, they will be compiled as binary resources.
- The Application.GetContentStream method returns a resource stream for a content data file that is located at the specified Uri.
- Either the DecodePixelWidth or DecodePixelHeight property of the image source to the desired height and width of each rendered image. This is because the application memory can be saved significantly required to load the image.
- In WPF user interface, WPF controls can display different kinds of contents on WPF controls such as images, graphics, formatted text, etc.
- WPF has provided new graphics system that uses device-independent units enabling resolution and device independence to client screens. Each device independent pixel automatically scales with the dots-per-inch setting of the client computer.
- The DecodePixelWidth property in the BitmapImage tag is set to the same width as the image width, as you will prevent the application from caching the full size and just scaling down to the 200 pixel width.
- A DrawingImage object is lightweight and uses less resources and hence is recommended for background and low resolution images. It is a Microsoft recommendation that you always decode images to the desired size rather than having the default size simply resized on display.
Binding to data sources
- If an application needs to access a particular to a data source and have used data binding. You need all the components on the application’s page to have access to this data source. This can be accomplished by simply adding the required data source into the section of the main container control.
- In order to bind specific text boxes to specific properties of a data source, you will need to first create the binding object for the specific property, and then you can use the SetBinding method to associate that binding object (and hence the underlying data source property) with the text box.
- The following XAML code will execute properly without causing any error: . In the above code, you need to identify the resource and in this case, a template is a static resource that you wish to bind to.
- The BindingOperations.ClearBinding method removes the data binding from a property if the current property of a control is data bounded.
- The Binding Mode should not be set to OneTime, as it causes the text boxes to only be updated when the application starts or when the data context changes.
- If an application uses data binding with the data source being a database on the local network, and part of the modifications involves moving all data access to a Web service. The data access methods must be changed accordingly. This can be accomplished by taking the following actions:
- Call the Web service method after creating a reference to the Web service.
- Set the DataContext property of the appropriate control or window to the returned object.
- Create data bindings to the properties of the object in which the DataContext property has been set.
- The BindingOperations.ClearBinding method removes the data binding from a property if the current property of a control is data bounded.
- The FallBackValue property of the BindingBase class is used to specify a default value when the binding load process fails to return a valid value. This default value is of the same type as the target property.
- The element tag is used to specify a list of data bindings that are ordered from highest priority to lowest priority. If the highest priority data binding returns a value successfully when it is processed, then there is no need to process other data bindings in the list.
- An application has several controls that need to display data from a database table. This can be accomplished by using data binding and by adding the required data source into the Resources section of the main container control.
- If an end user simply select a color from the ComboBox control, the background of the application page changes immediately to that color. This can be achieved by binding the ComboBox to the Canvas using the following code, after creating the ComboBox with the appropriate colors:
- When the list of customer names in the combo box is changed, the data source must be updated and accordingly the data in the text boxes is updated too. In accomplishing this task, you must update the currently changed selected item in the combo box. When the data source is updated, the data in the text boxes should also be updated by setting the text boxes to TwoWay directional binding mode.
- The OneWay directional binding mode specifies the direction of the binding updates. It updates the binding target property when the binding source is changed.
- The Binding.UpdateSourceTrigger property sets a value to determine the timing of binding source updates.
- The first and last name of all employees in a list box is displayed by binding them to the collection of the clsEmployee class. In order to accomplish this, you should take the following actions:
- Add the collection of the clsEmployee class as a resource.
- Set the resource as the ItemsSource for the list box.
- Set the IsSynchronizedWithCurrentItem property to true in order to get the current individual item in the data source to synchronize.
- Use the Binding Path to bind a specific property bound to the list box.
- Some collections can be used as data sources to bind controls such as combo boxes by taking the following actions:
- At first, add the collection to the application page as a resource.
- Then, use the collection as a static resource for the controls data binding.
- The Source attribute in the element must define the full path of the XML data source to identify the URI.
- If a user desire to convert the dates to a common format when they are bound to ensure that they are saved to the data source in the appropriate format, the following actions should be taken:
- Firstly, create a class that implements the IValueConverter interface.
- Secondly, create a method to convert the data you need converted.
- Lastly, use that class you created in the binding with the controls.
- A custom error template is implemented in the binding process by adding the Validation.ErrorTemplate tag to the controls definition.
- If a user enters different numbers of decimal digits, the data is able to convert in a common decimal format before it is added to the data source. This can be accomplished by taking the following actions:
- Create a class that implements the IValueConverter interface.
- Create methods in the class to convert all decimal input to a common format and round to the appropriate number of decimal places.
- Then, implement that class as part of the XAML binding code using the converter tag.
- To handle the validation within the custom objects such as customer, employee, etc., you should take the following steps:
- Firstly, you need to write the validation code into the classes.
- Secondly, set the ValidatesOnDataErrors property to true in the data binding code.
- The Validation.ErrorTemplate attached property is set to a custom ControlTemplate object, and a style trigger is used to provide visual feedback to users if they enter an invalid value on an application user interface.
- If a user enters an invalid data into a particular data bound control, a red exclamation mark appears next to that data bound control and a tool tip with an error message appears when a user moves the mouse over the data bound control.
- The ErrorProvider control is used to provide a user interface for indicating whether or not a control has an error associated with it. Generally, it is used in association with data-bound controls.
- The SetError method of the ErrorProvider control is used to specify the error description string for a specified control.
- The Interval property of the Timer component is used to get or set the time (in milliseconds) between the timer ticks in an application.
- You do not want the data source to be updated until the user moves to the next page, allowing them to change or cancel any edits they have made. This can be achieved by setting the UpdateSourceTrigger property value to Explicit that updates the binding source only when you call the UpdateSource method.
- You need to ensure that the controls in the user interface of the application are aware of changes that might occur outside the application. This can be accomplished by setting the NotifyOnSourceUpdated property to true if the SourceUpdated event is raised and when the binding source value is updated.
- The UpdateSourceTrigger property value is set to PropertyChanged to update the binding source immediately whenever the binding target property changes.
- The NotifyOnSourceUpdated property gets or sets a value to indicate whether to raise the SourceUpdated event when a value is transferred from the binding target to the binding source.
- When you set the UpdateSourceTrigger value to Explicit, the source value only changes when the application calls the UpdateSource method.
Pass MCTS: Microsoft Visual Studio 2008 in a first attempt:
- 70-502-CSHARP, MCTS: C# .NET 3.5 C# Windows Presentation Foundation Application Development
- 70-503-CSHARP, MCTS: C#.NET Framework 3.5 – Windows Communication Foundation Application
- 70-504-CSHARP, MCTS:.NET C# 3.5 – Windows Workflow Foundation Application Development
- 70-536-CSHARP, C# .NET Framework Application Development Foundation
- 70-561-CSHARP, TS: Microsoft .NET Framework 3.5, ADO.NET Application Development
Customizing appearance
- The TargetType property sets the type for which a specific style is defined. Therefore, the intended style can be set for each TextBlock element without taking extra development effort.
- The control properties are set inside the app.xaml file by using a
tag with its Setter property.</li> <li> In order to get a consistent look to an application’s controls, the following are the steps that should be taken: <ul> <li>Firstly, create a <Style> within a Resources collection and define a key for the style.</li> <li>Secondly, create the <Setter> elements within the style to set the various properties of the target control to specific values. </li> <li>Lastly, reference the style from the style attribute within the controls XAML tag.</li> </ul> </li> <li>In WPF, a trigger is a feature that allows a user to dynamically change the appearance and behavior of a control in an application without having to create a new control. It sets properties of controls or starts its actions when a property value changes or when an event is raised.</li> <li> Adding a trigger to the menu item style definition is very quick and simple, and fully implements the requirements.</li> <li> If a user wants to change the appearance of every item listed in a ListBox control of the application, it is better to add a trigger to the ListBox style definition.</li> <li> Add a trigger to the button style definition, so that the font of buttons will change when the mouse is over them.</li> <li>Set the animation’s FillBehavior property to <b>Stop</b> in order to stop the animation from overriding the TextBox controls property.</li> <li> A storyboard can organize animations and apply them in groups to one or more Storyboard objects. It supports user interactions through which a user can have more control over an application. It also supports XAML files.</li> <li> In a XAML code, when a Storyboard is used to animate an image, it is necessary to have the From and To properties to move an image from one location to another.</li> <li>The best way to access application resources is to place a reference to the style in the button’s XAML code as Style=”{StaticResource StyleName}”.</li> <li> The best way to address the issue of images changing at runtime is to enumerate the images in the image folder and use the Application.Current.Resources.Add method to add the images as application-wide resources.</li> <li>Control templates are created within styles and can be used to dramatically alter the appearance of any control.</li> <li> A control template is a feature that defines the structure and appearance of a WPF control. This separates the appearance of the control from its functionality. A control’s appearance can be drastically changed by redefining its ControlTemplate object.</li> <li> Control templates are specifically designed in the application’s XAML code so that the appearance of a control can be altered as desired. Once implemented, these control templates can override the properties for a specific Button control to be applied throughout the application.</li> <li>It is a best practice to create your user interface with all the required controls by using XAML. Using XAML allows you to alter the text via the <uc:kwd>xml:lang</uc:kwd> attribute and display it in the language of your choice.</li> <li> The most efficient way to use data as a resource in your application is to create a ResourceDictionary method to make the application localizable.</li> <li> The following are the actions for the localization of the Arabic language users: <ul> <li>Set the <b>xml</b> encoding to UTF-8 or UTF-16. For example, ?xml encoding=”UTF-16″?. The UTF encoding is used for international encoding. </li> <li>Set the xml:lang attribute to Arabic. For example, xml:lang=”ar-DZ” </li> <li>Set the flow direction from right to left, as Arabic language flows from right to left.</li> </ul> </li> <li> The SizeToContent property in an XAML code sets a value to indicate whether an application window will automatically size itself to fit the size of its content.</li> <li> The best way to handle the situation is to change the flow direction in the Window’s XAML code to the appropriate direction either in a right-to-left or in a left-to-right direction. WPF provides bi-directional controls.</li> </ul> <p><b> Configuring and deploying WPF applications</b></p> <ul> <li>WPF standalone applications require either ClickOnce or Microsoft Windows Installer deployment to deploy easily. The Microsoft Windows Installer deployment technology is used in which full trust is automatically granted to standalone applications.</li> <li> If the ClickOnce deployment technology is used, a user should accept the security warning dialog box displayed by ClickOnce in order to successfully install a WPF standalone application as well as to grant full trust to it.</li> <li> The Click Once installation technology allows users who do not have administrative rights to install packages, and it allows for automatic updating of the software.</li> <li> When a system dll’s is installed along with the standard application installation, an error will occur saying that the dll’s should be excluded because ‘source file is under Windows protection’.</li> <li> An application can be deployed on a Web server by copying the files manually on the Web server, using the Copy Project command of Visual Studio .NET, and by using the Windows Installer package.</li> <li>The Version setup project property contains information about the post-build event execution and search paths for assemblies and files in order to determine versioning.</li> <li>By default, an XML browser-hosted application (XBAP) requests the Internet Zone CAS set of permissions. WPF provides functionality that can be used safely in a partial trust environment. However, some functionality cannot be safe in a partial trust environment. They can include: </li> <li> Web browser (XBAP) applications are only partially trusted and are not allowed access to many system resources, including the SaveFileDialog class and the XAML serialization process.</li> <li> The System.Security.Permissions namespace has the IsPermissionGranted method that determines whether the application has permission for performing a specific operation before attempting it.</li> <li>You should deploy the application to clients using either XCOPY or Windows Installer deployment, as you need to access the local databases and Windows registry stored in the local computer.</li> <li> The following steps are required for preparing the deployment of an XBAP application: <ul> <li>Copy the .exe file for the application and the associated manifests to a Web server.</li> <li>Create a hyperlink on the application’s Web page to navigate to the deployment manifest. </li> <li>Use the ClickOnce deployment to automatically download and publish the application.</li> </ul> </li> <li> An XBAP application is a compiling application that requires three files, namely the .exe, .xbap, and .exe.manifest files, to be deployed. These files are produced when an XBAP application is built by using the MSBuild technology.</li> <li> In order to run an XBAP application, the Microsoft .NET Framework with version 3.0 must be installed on the client computer. When the XBAP application are launched from the Internet Explorer with version 7.0, the IE 7.0 will automatically detect whether or not the client computer has installed .NET Framework 3.0.</li> <li> The IsApplication property for the application’s folder specifies whether a Web server application root will be created for the folder. If this property is set to true, the AlwaysCreate property must also be set to true.</li> <li>The ClickOnce installation method is designed specifically to make updates automatic.</li> <li> A merge module project should be created to update the existing .msi file.</li> <li>The Caspol.exe file runs on the client machine to set security settings in order to have full access to the computer.</li> <li> An XBAP application that has a browser-scope navigation to contents is considered safe only under the following conditions: </li> <li>A user navigates a browser-related contents by clicking a Hyperlink element.</li> <li>The content that is to be navigated by a user is located on the Internet or the local intranet. </li> <li>A browser navigation is considered safe when either the http:, https:, file:, or mailto: protocol is used.</li> <li>ClickOnce technology overcomes three major deployment issues. These issues include difficulties in updating Windows-based applications, dependence of multiple application programs on shared components, and allowing permissions only to administrative users for application installations.</li> </ul>