WPF – Controls

WPF – Controls ”; Previous Next 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 − 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. 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 3rd Party Controls Use third-party controls in your WPF applications. We will discuss all these controls one by one with their implementation. Print Page Previous Next Advertisements ”;

WPF – Dependency Properties

WPF – Dependency Properties ”; Previous Next 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” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:local = “clr-namespace:WPFDependencyProperty” Title = “MainWindow” Height = “350” Width = “604”> <Grid> <Button Height = “40” Width = “175” Margin = “10” Content = “Dependency Property”> <Button.Style> <Style TargetType = “{x:Type Button}”> <Style.Triggers> <Trigger Property = “IsMouseOver” Value = “True”> <Setter Property = “Foreground” Value = “Red” /> </Trigger> </Style.Triggers> </Style> </Button.Style> </Button> </Grid> </Window> 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}”> 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. 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(); } 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” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:views = “clr-namespace:WpfApplication3” Title = “MainWindow” Height = “350” Width = “604”> <Grid> <views:UserControl1 SetText = “Hellow World”/> </Grid> </Window> 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. Print Page Previous Next Advertisements ”;

WPF – XAML Overview

WPF – XAML Overview ”; Previous Next 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” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” Title = “MainWindow” Height = “350” Width = “525”> <Grid> </Grid> </Window> The above XAML file contains different kinds of information. The following table briefly explains the role of each information. Information Description <Window It is the opening object element or container of the root. x:Class = “Resources.MainWindow” It is a partial class declaration which connects the markup to the partial class code defined behind. xmlns = “http://schemas.microsoft.com/win fx/2006/xaml/presentation” Maps the default XAML namespace for WPF client/framework xmlns:x = “http://schemas.microsoft.com/w infx/2006/xaml” XAML namespace for XAML language which maps it to x: prefix > End of object element of the root <Grid> </Grid> It is starting and closing tags of an empty grid object. </Window> Closing the object element 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.Content>Click Me</Button.Content> <Button.Height>30</Button.Height> <Button.Width>60</Button.Width> </Button> Example of Object with Child Element: StackPanel contains Textblock as child element <StackPanel Orientation = “Horizontal”> <TextBlock Text = “Hello”/> </StackPanel> 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 − 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 = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” Title = “MainWindow” Height = “350” Width = “604”> <StackPanel> <Button x:Name = “button” Content = “Click Me” HorizontalAlignment = “Left” Margin = “150” VerticalAlignment = “Top” Width = “75” /> </StackPanel> </Window> 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(); 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. 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. Print Page Previous Next Advertisements ”;

WPF – Quick Guide

WPF – Quick Guide ”; Previous Next WPF – Overview 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 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 (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 WPF – Environment Setup 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 VisualStudio. Download the files and follow the steps given below to set up WPF application development environment on your system. After the download is complete, run the installer. The following dialog will be displayed. Click the Install button and it will start the installation process. Once the installation process is completed successfully, you will get to see the following dialog box. Close this dialog box and restart your computer if required. Now open Visual Studio from the Start Menu which will open the following dialog box. Once all is done, you will see the main window of Visual Studio. You are now ready to build your first WPF application. WPF – Hello World 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. Click on File > New > Project menu option. The following dialog box will be displayed. Under Templates, select Visual C# and in the middle panel, select WPF Application. Give the project a name. Type HelloWorld in the name field and click the OK button. By default, two files are created, one is the XAML file (mainwindow.xaml) and the other one is the CS file (mainwindow.cs) On mainwindow.xaml, you will see two sub-windows, one is the design window and the other one is the source (XAML) window. 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. In mainwindow.xaml file, the following XAML tags are written by default. <Window x:Class = “HelloWorld.MainWindow” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” Title = “MainWindow” Height = “350” Width = “604”> <Grid> </Grid> </Window> By default, a Grid is set as the first element after page. Let’s go to the toolbox and drag a TextBlock to the design window. You will see the TextBlock on the design window. When you look at the source window, you will see that Visual Studio has generated the XAML code of the TextBlock for you. Let’s change the Text property of TextBlock in XAML code from TextBlock to Hello World. <Window x:Class = “HelloWorld.MainWindow” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” Title = “MainWindow” Height = “350” Width = “604”> <Grid> <TextBlock x:Name = “textBlock” HorizontalAlignment = “Left” Margin = “235,143,0,0” TextWrapping = “Wrap” Text = “Hello World!” VerticalAlignment = “Top” Height = “44” Width = “102” /> </Grid> </Window> Now, you will see the change on the Design Window as well. When the above code is compiled and executed, you will see the following window. Congratulations! You have designed and created your first WPF application. WPF – XAML Overview One

WPF – Triggers

WPF – Triggers ”; Previous Next 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 = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” Title = “MainWindow” Height = “350” Width = “604”> <Window.Resources> <Style x:Key = “TriggerStyle” TargetType = “Button”> <Setter Property = “Foreground” Value = “Blue” /> <Style.Triggers> <Trigger Property = “IsMouseOver” Value = “True”> <Setter Property = “Foreground” Value = “Green” /> </Trigger> </Style.Triggers> </Style> </Window.Resources> <Grid> <Button Width = “100” Height = “70” 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 with some properties. When the checkbox is checked, it will change its foreground color to red. <Window x:Class = “WPFDataTrigger.MainWindow” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” 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}” Value = “true”> <Setter Property = “TextBlock.Foreground” Value = “Red”/> <Setter Property = “TextBlock.Cursor” Value = “Hand” /> </DataTrigger> </Style.Triggers> </Style> </TextBlock.Style> </TextBlock> </StackPanel> </Window> When the above code is compiled and executed, it will produce the following output − 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” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” Title = “MainWindow” Height = “350” Width = “604”> <Grid> <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” KeyTime = “0:0:3″/> </DoubleAnimationUsingKeyFrames> <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty = “Height” 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> </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. Print Page Previous Next Advertisements ”;

WPF – Interaction

WPF – Interaction ”; Previous Next 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 = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” xmlns:local = “clr-namespace:WPFBehaviors” xmlns:i = “http://schemas.microsoft.com/expression/2010/interactivity” xmlns:ei = “http://schemas.microsoft.com/expression/2010/interactions” 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 = “301.524”/> <EasingDoubleKeyFrame KeyTime = “0:0:2” Value = “2.909”/> </DoubleAnimationUsingKeyFrames> <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> <Button x:Name = “button” Content = “Play” HorizontalAlignment = “Left” Height = “24.238” Margin = “63.867,0,0,92.953” VerticalAlignment = “Bottom” Width = “74.654”> <i:Interaction.Triggers> <i:EventTrigger EventName = “Click”> <ei:ControlStoryboardAction Storyboard = “{StaticResource Storyboard1}”/> </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. 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. 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. Create a new WPF project with the name WPFDragAndDrop. Drag five rectangles to the design window and set the properties as shown in the following XAML file. <Window x:Class = “WPFDragAndDrop.MainWindow” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” xmlns:local = “clr-namespace:WPFDragAndDrop” mc:Ignorable = “d” Title = “MainWindow” Height = “402.551” Width = “604”> <Grid> <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> The first rectangle is the target rectangle, so the user can drag the color from the other rectangle to the target rectangle. 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. 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 4th 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. Print Page Previous Next Advertisements ”;

WPF – Resources

WPF – Resources ”; Previous Next 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. Let’s create a new WPF project with the name WPFResouces. Drag two Rectangles and set their properties as shown in the following XAML code. <Window x:Class = “WPFResources.MainWindow” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” 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}” /> <Rectangle Height = “50” Margin = “20” Fill = “{DynamicResource brushResource}” /> <Button x:Name = “changeResourceButton” Content = “_Change Resource” Click = “changeResourceButton_Click” /> </StackPanel> </Window> 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. 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. 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. 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 = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” 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 = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml”> <SolidColorBrush x:Key = “brushResource” Color = “Blue” /> </ResourceDictionary> Here is the implementation in app.xaml − <Application x:Class=”WPFResources.App” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” StartupUri = “MainWindow.xaml”> <Application.Resources> <ResourceDictionary Source = ” XAMLResourcesResourceDictionariesDictionaryWithBrush.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). Print Page Previous Next Advertisements ”;

WPF – Multimedia

WPF – Multimedia ”; Previous Next 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 = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” 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> </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; 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. Create a new WPF project with the name WPFTextToSpeech. We will need System.Speech assembly to add as reference for SpeechSynthesizer class to work. Right click on References and Select Add Reference. Reference Manager dialog will open. Now check the System.Speech check box Click the Ok button. You can see the System.Speech assembly in your References. Now drag a button and a textbox into the design window from the toolbox. The following XAML code creates a button and a textbox, and initializes them with some properties. <Window x:Class = “WPFTextToSpeech.MainWindow” xmlns = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” xmlns:local = “clr-namespace:WPFTextToSpeech” mc:Ignorable = “d” Title = “MainWindow” Height = “350” Width = “604”> <Grid> <Button x:Name = “button” Content = “Speak” HorizontalAlignment = “Left” Margin = “218,176,0,0” VerticalAlignment = “Top” Width = “75”/> <TextBox x:Name = “textBox” HorizontalAlignment = “Left” Height = “23” Margin = “60,104,0,0” TextWrapping = “Wrap” VerticalAlignment = “Top” Width = “418”/> </Grid> </Window> Here is the simple implementation in C# which will convert the Text inside the textbox into spoken words. using System.Speech.Synthesis; using System.Windows; namespace WPFTextToSpeech { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void button_Click(object sender, RoutedEventArgs e) { if (textBox.Text != “”) { SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer(); speechSynthesizer.Speak(textBox.Text); } else { MessageBox.Show(“Write some thing in the textbox!”); } } } } When you compile and execute the above code, it will produce the following window. Now, type Hello World inside the textbox and click the Speak button. It will produce the sound “Hello World”. If you don’t type anything in the textbox, then it will flash the following message. We recommend that you execute the above examples. Print Page Previous Next Advertisements ”;

WPF – Nesting Of Layout

WPF – Nesting of Layout ”; Previous Next 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 = “http://schemas.microsoft.com/winfx/2006/xaml/presentation” xmlns:x = “http://schemas.microsoft.com/winfx/2006/xaml” xmlns:d = “http://schemas.microsoft.com/expression/blend/2008” xmlns:mc = “http://schemas.openxmlformats.org/markup-compatibility/2006” 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> <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> </StackPanel> </Grid> </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 other nesting layouts. Print Page Previous Next Advertisements ”;

WPF – Useful Resources

WPF – Useful Resources ”; Previous Next The following resources contain additional information on WPF. Please use them to get more in-depth knowledge on this. WPF Online Training Featured 32 Lectures 2.5 hours Tutorialspoint More Detail C# interfaces – Blazor, API, UWP, WPF, Office 31 Lectures 2.5 hours Taurius Litvinavicius More Detail Easy WPF in C# Windows Presentation Foundation for Beginners 333 Lectures 59.5 hours Abdullah Musavi More Detail Print Page Previous Next Advertisements ”;